开发者

Can a class method be both inline and static?

开发者 https://www.devze.com 2022-12-18 05:22 出处:网络
Doe开发者_如何学Gos it even make sense?static means that the method isn\'t associated with an instance of a class. (i.e. it has no \"this\" pointer).

Doe开发者_如何学Gos it even make sense?


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.


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


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


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++.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号