C++ Isn't this a useless inline declaration?

258 Views Asked by At

This is another question about inlining a function.
But I will take possible comments and answers right away:

  1. Defining a function inside a class makes it inline automatically.
  2. The same behaviour can be achieved by marking a function with inline outside of the class.
  3. An inline function doesn't have to be inlined. It is completly up to the compiler to inline it.

Now, my question:
When inlining a function means to copy the body to the place where it is being called.
Isn't it right to assume that the compiler will not inline it if it accesses private or protected members?
The programm would literally not be able to access the members right?

I want to know that because to me it must look quite weird if someone inlines a function that obviously cannot be inlined.

Here is an example:

//Declaration
class Controller
{
public:
    bool bHasTarget();

private:
    const Object* pTarget;
};


//Definition
inline bool Controller::bHasTarget(){
    return !(pTarget == nullptr); //<- This cannot be inlined...Can it?
}
2

There are 2 best solutions below

2
On BEST ANSWER

The Compiler can Access everything. The restrictions are only valid for the programmer. This means there are no restrictions for the Compiler to Access any variables! At the end every variable is just translated to an address which can be accessed. So for the Compiler it is no Problem to inline the code you provided!

There are also some "cheats" to Access private variables as a programmer. e.g

struct foo
{
private:
    int a;
    int b;
};

...
foo test;
int *cheat = reinterpret_cast<int*>(&test);
cheat[0] = 1;    //This would Change a
...
0
On

An inline function may not be inlined by the compiler. It is completly up to the compiler to inline it.

Compiler may inline but it might not. It's not guaranteed to.

Isn't it right to assume that the compiler will not inline it if it accesses private or protected members?

No, it's not right to assume so. Accessing private or protected members does not prevent inlining.

The programm would literally not be able to access the members right?

The program is literally able to access private and protected members. The function is a member, whether it's inlined or not.

To elaborate a bit, the compiler checks that the program does not break the access rules before any inlining optimization is done. After the check is passed, the access specifiers have zero meaning to the produced program and does not limit any optimization.

The example function can be inlined.