Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class method be both inline and static?

Tags:

c++

Does it even make sense?

like image 628
static_rtti Avatar asked Jan 25 '10 16:01

static_rtti


4 Answers

static means that the method isn't associated with an instance of a class. (i.e. it has no "this" pointer).

inline is a compiler hint that the code for the method ought to be included inline where it is called, instead of being called via a normal branch. (Be aware that many compilers ignore this keyword, and use their own metrics to decide whether to inline).

These are orthogonal (unrelated) concepts, so there's no particular reason they couldn't be combined.

like image 64
stusmith Avatar answered Nov 12 '22 12:11

stusmith


I don't see why not. A static class member is like a standalone function with private access to the other member functions.

like image 33
Dimitri C. Avatar answered Nov 12 '22 10:11

Dimitri C.


Yes, there is no reason these can't be combined.

like image 2
JaredPar Avatar answered Nov 12 '22 10:11

JaredPar


You can.

However, the GCC manual says that the function will not be integrated by the compiler into the code if:

  1. you call the method before you define it, or
  2. there are any recursive calls within the definition.

Source: GCC Manual - discusses both C and C++.

I tried coding up both of these scenarios in Visual C++ using a small sample class called Class1. Here's the relevant snippet, where incTest is defined in my Class1.h file.

// test static inline method - based on the GCC manual's C example
static inline int inc (int *a)
{ 
    return (*a)++;
}

// test recursive call in a static inline method
static inline int fac (int x)
{
    return x * fac(x-1);
}

int Class1::incTest(int* x)
{
    return inc(x);
}

This is the version of it that compiles successfully. However, if I'm using Visual C++ and I move the definition of inc() to after incTest()'s definition, the file does not compile successfully, giving me an error at the call to inc() saying, "Identifier not found".

Edit: revised my answer to take into account comments and results of my testing in Visual C++.

like image 1
David Avatar answered Nov 12 '22 12:11

David