pointers-inline meaning? [duplicate] - c++

This question already has answers here:
what is/are the purpose(s) of inline?
(9 answers)
Closed 8 years ago.
I have come across this while reading a program in C++
inline Controller* Get_it() { // ... bla bla
I don't understand what this means. Does this imply the definition of Get_it function? I have searched for files where Get_it function is defined, but didn't find it. I think that the syntax a* b means that b is pointer to point to objects of structure a, but there is no stucture Controller. There is though a class Controller defined somewhere else.
Thank you in advance people. I am new to C++ and I am trying to understand.

The function Get_it returns a Controller*. That's a pointer to a Controller, which is a type that must be declared somewhere above this point in the translation unit. The function is marked inline which is a hint to the compiler that it can inline the code, basically copying the function body into every place it is called from.
These two things are separate. The pointer is not inline, the function is.

The keyword inline affects what it being defined, and is only
applicable to functions. Formally, it allows (and in fact
requires) multiple definitions of the function. It is also
a "hint" to the compiler that it should try to generate the code
for the function directly at the call site, rather than to
generate a call elsewhere. (The motivation for the formal
definition is that the compiler typically cannot generate the
code inline unless it has access to the definition.)

First, you should get yourself a good book on C++. Secondly, that is a pointer to a Controller object (a class in memory). It is returned by the function and the function is defined inline, meaning that it will be copied entirely to the callsite wherever it is called.
The inline word is a suggestion to the compiler to do inlining where sensible, but because you seem to indicate the function is defined inside the class declaration, it will be inlined by the compiler automagically.

The inline keyword doesn't apply to the pointer (the return value of the function), but to the function itself. So here you declare (and define) an inline function which returns a pointer-to-Controller.

The inline keyword defines an method as inline1, no matter where it get's implemented. The signature above means, that the function Get_it() returns an pointer to an Controller object. The function itself is inline.
1 Inline means, that the method get's not addressed through an vtbl, but get's directly allocated in the object's memory, so that there is no indirection when calling the method on an object instance, but the object instance itself grows in memory size.

Related

inline this function, does make sense?

I have the next member function:
template <typename T>
inline T Foo::Read(const DWORD addr) const // Passing by value.
{
T buffer;
ReadProcessMemory(m_processHandle, (LPVOID)addr, &buffer, sizeof(T), NULL);
return buffer;
}
If I'm not wrong, when the compiler inlines a function, it avoids calling the function and put the code of the called function into the caller function.
So in the caller function (assuming an integer return type) I would want something like:
ReadProcessMemory(m_processHandle, (LPVOID)addr, &bufferOfTheCaller, sizeof(int), NULL);
I have three questions about this:
1) What would happen with the variable that we return from the function?
Isn't the declaration of the variable buffer performed in run time?
2) In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
3) What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition? If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
It's important to note that the inline keyword has nothing to do with inlining calls to the function. All it does is allow the function to be defined in multiple translation units, as long as all of the definitions are the same.
What the inline keyword does is let you define a function in a header file that will be included in multiple translation units. This may give the compiler a better opportunity to inline call to that function, since it has the full definition available in multiple translation units, but it is not a command or even a hint that you want the compiler to do so. The compiler will decide on its own if it should or shouldn't inline a call to any given function. There are compiler-specific extensions that you can use if you do want to force calls to a function to be inlined, but that is not what the inline keyword does.
With that out of the way, I'll add that the compiler inlining a function call doesn't change the rules of C++ at all. It isn't a textual replacement, like a preprocessor macro. The compiler will figure out how to insert the logic from the called function into the caller. At that point, things like C++ variables don't really exist. If your call looks something like this:
int someValue = myFoo.Read(someAddress);
then the compiler can easily transform that into something like this:
int someValue;
ReadProcessMemory(myFoo.m_processHandle, (LPVOID)someAddress, &someValue, sizeof(int), NULL);
due to the as-if rule. Both of those snippets result in the same observable behavior, so the compiler can freely transform between them.
What would happen with the variable that we return from the function?
It will be destroyed, because the return value was discarded by the function call expression.
Isn't the declaration of the variable buffer performed in run time?
Declarations happen at compile time.
In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
If the compiler knows the definition of the function, then it could expand it inline. Whether it should, or whether it will do so depend on many factors. Size of a function is a heuristic that may affect the choice that the compiler makes.
What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition?
In one case the definition is inside the class and in the other case it is outside. There is no other difference.
If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
If you want to define a member function inline, but want to define it outside of the class definition, then you must declare the function inline within the class definition - except a function template, which is implicitly inline.
If you want to define the member function within the class definition, then you don't need to explicitly declare it inline; it will be so implicitly.
If you want to not define the function inline, then you must define the function outside the class definition and must not use the inline keyword.
If I'm not wrong, when the compiler inlines a function, it avoids calling the function and put the code of the called function into the caller function.
Yes, but inline has little to do with that.
1) What would happen with the variable that we return from the function? Isn't the declaration of the variable buffer performed in run time?
The compiler, inlining or not, will have to reserve some space for buffer, typically on the stack.
In other words, there is no bufferOfTheCaller. If your function is inlined, buffer will be in the caller's stack frame; otherwise, it will be put in the callee's stack frame.
2) In this case ReadProcessMemory is a huge function from the WinAPI, should the compiler still able to inline this function?
It does not matter how big the implementation of ReadProcessMemory is, your code just performs a function call to it, which is tiny. An optimizing compiler is likely to inline your function.
3) What is the difference between leaving the member function defined inside the class definition and declare it with the keyword inline outside the class definition?
No difference.
If I want to use inline keyword, Do I have to put the inlined function in the same file .h or?
The inline keyword is not about inlining. If you want to put the definition of a function in a header file, you will likely need inline to prevent redefinition errors.

Why does my compiler insist on unused function definitions only for virtual? [duplicate]

I find it quite odd that unused virtual functions must still be defined unlike unused ordinary functions. I understand somewhat about the implicit vtables and vpointers which are created when a class object is created - this somewhat answers the question (that the function must be defined so that the pointers to the virtual function can be defined) but this pushes my query back further still.
Why would a vtable entry need to be created for a function if there's absolutely no chance that virtual function will be called at all?
class A{
virtual bool test() const;
};
int main(){
A a; //error: undefined reference to 'vtable for A'
}
Even though I declared A::test() it was never used in the program but it still throws up an error. Can the compiler not run through the program and realise test() was never called - and thus not require a vtable entry for it? Or is that an unreasonable thing to expect of the compiler?
Because it would inevitably be a very difficult problem to solve on the compiler writer's part, when the usefulness of being able to leave virtual functions undefined is at best dubious. Compiler authors surely have better problems to solve.
Besides, you ARE using that function even though you don't call it. You are taking its address.
The OP says that he already knows about vtables and vpointers, so he understands that there is a difference between unused virtual functions and unused non-virtual functions: an unused non-virtual function is not referenced anywhere, while a virtual function is referenced at least once, in the vtable of its class. So, essentially the question is asking why is the compiler not smart enough to refrain from placing a reference to a virtual function in the vtable if that function is not used anywhere. That would allow the function to also go undefined.
The compiler generally sees only one .cpp file at a time, so it does not know whether you have some source file somewhere which invokes that function.
Some tools support this kind of analysis, they call it "global" analysis or something similar. You might even find it built-in in some compilers, and accessible via some compiler option. But it is never enabled by default, because it would tremendously slow down compilation.
As a matter of fact, the reason why you can leave a non-virtual function undefined is also related to lack of global analysis, but in a different way: if the compiler knew that you have omitted the definition of a function, it would probably at least warn you. But since it does not do global analysis, it can't. This is evidenced by the fact that if you do try to use an undefined function, the error will not be caught by the compiler: it will be caught by the linker.
So, just define an empty virtual function which contains an ASSERT(FALSE) and proceed with your life.
The whole point of virtual functions is that they can be called through a base class pointer. If you never use the base class virtual function, then, why did you define it ? If it is used, they you either have to leave the parent implementation (if it's not pure virtual), or define your own implementation, so that code using your objects through the base class can actually make use of it. In that case, the function is used, it's just not used directly.

Definition of a class's private integral constant: in the header or in the cpp file?

Subject has been addressed mostly here (Where to declare/define class scope constants in C++?)
and in particular here.
What I would like to fully understand, in case of integral constants, is there any difference between:
//In the header
class A {
private:
static const int member = 0; //Declaration and definition
};
And:
//In the header
class A {
private:
static const int member; //Only declaration
};
//In the cpp
const int A::member = 0; //Definition
(I understand that the second might have the advantage that if I change the value of the constant, I have to recompile only one file)
Side questions:
What happens for example with an inline method defined in the header that access member? Will it simply be not inlined? What would happens if, going to one extreme, all methods were defined in the header file as inline methods and all constants were defined in the cpp file?
Edit:
My apologizes: I thought it was not necessary, but I missed the fact that the member is static. My question stays, but now the code is legal.
If, as it was before the question was changed to make it static, it's a non-static member, then it can only be initialised in the constructor's initialiser list or (since 2011) in the member's declaration. Your second example was ill-formed.
If it's static, then you need a definition if it's odr-used: roughly speaking, if you do anything that requires its address rather than just its value. If you only use the value, then the first example is fine. But note that the comment is wrong - it's just a declaration, not a definition.
If you do need a definition, then it's up to you whether you specify the value in the declaration or the definition. Specifying it in the declaration allows better scope for optimisation, since the value is always available when the variable is used. Specifying it in the definition gives better encapsulation, only requiring one translation unit to be recompiled if it changes.
What happens for example with an inline method defined in the header that access member? Will it simply be not inlined?
There's no reason why accessing a data object defined in another translation unit should prevent a function from being inlined.
There are two points of view to take into account, namely visibility and addressing.
Note that the two are orthogonal, for you can actually declare the variable as initialized and still define it in a translation unit so it has an effective address in memory.
Visibility
Visibility affects the usage of the variable, and has some technical impacts.
For usage in template code as a non-type template parameter, the value must be visible at the point of use. Also, in C++11, this might be necessary for constexpr usage. Otherwise, it is not necessary that the value be visible.
Technically a visible value can trigger optimizations from the compiler. For example if (A::member) is trivially false so the test can be elided. This is generally referred to as Constant Propagation. While this may seem a good thing, at first glance, there is a profound impact though: all clients of the header file potentially depends on this value, and thus any change to this value means they should be recompiled. If you deliver this header as part of a shared library, this means that changing this value breaks the ABI.
Addressing
The rule here is quite simple: if the variable can be addressed (either passed by pointer or reference), then it needs to reside somewhere in memory. This requires a definition in one translation unit.
This is the question of data hiding. Whether you want to unveil internal class fields or not. If you are shipping a classes library and want to hide the implementation details then it is better to show in the interface as few entities as possible, then even a declaration of the private field member is too much.
I would just declare this value as a static variable inside a .cpp file.

Inline functions in c++ - conditions

Under What condition an inline function ceases to be an inline function and acts as any other function?
The Myth:
inline is just a suggestion which a compiler may or may not abide to. A good compiler will anyways do what needs to be done.
The Truth:
inline usually indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules(especially w.r.t One Definition Rule) for inline are followed.
Under What condition an inline function ceases to be an inline function and acts as any other function?
Given the quoted fact there is a deeper context to this question.
When you declare a function as static inline function, the function acts like any other static function and the keyword inline has no importance anymore, it becomes redundant.
The static keyword on the function forces the inline function to have an internal linkage.(inline functions have external linkage)
Each instance of such a function is treated as a separate function(address of each function is different) and each instance of these functions have their own copies of static local variables & string literals(an inline function has only one copy of these ).
It's at the discretion of the compiler.
But some cases just can't be inlined, like:
Recursive functions
Functions whose address is referenced somewhere
Virtual functions (there are some exceptions thought)
That depends on the compiler optimization.
Different compilers have different rules to make the code more efficient. But if you declare a function as inline, the compiler tends to respect your decision as long as none of it's rules says different.
Remember that the compiler can change completely the execution path of a method. For example, consider the next situation:
int MyClass::getValue()
{
return someVariable;
}
At compile time, there is little difference between declaring this kind of function as inline or not. Probably the compiler will make the attribute partially public and code:
myInstance->getValue()
as
myInstance->someVariable
So it's more an aesthetical decision in most cases.

What are the inlining rules within C++ classes?

From what I read somewhere long time ago, it seems that if you want class member function to be inlined during the compilation phase, the function has to be defined inside class declaration block.
But this has a downside of a detail leak. IMHO, other programmers should only see class interface when opening .h file.
Is the first statement still true in modern C++, was it ever? Is there a way to force inlining for functions that are declared, preferably in another file altogether?
Is it generally better to keep short member functions inside class declaration block, or not?
It seems that if you want class member function to be inlined during the compilation phase, the function has to be defined inside class declaration block.
That is not really true. A function that is defined inside the class definition is implicitly marked as inline. But you don't need to defined the function inside the class for it to be inline, you can explicitly request it:
struct X {
void f();
};
inline void f() {}
The inline keyword on the other hand, does not mean that the function will be inlined, but rather that it can be defined in multiple translation units, that is, if multiple translation units include the same header that contains that definition, the linker will not fail with a multiple definition error.
Now, on actual inlining, the compiler can decide to inline or not any function, regardless of whether the function is declared as inline provided that it sees the definition of that function (the code that it will inline), which is the reason why in general functions that are meant to be inlined should be defined in the header (either inside the class definition or marked inline outside.
Additionally, newer toolchains can perform whole program optimization or other link time optimizations, by which the linker can also decide that a function should be inlined. In this case, the function definition needs not be visible at the call site, so it could be defined inside the .cpp file. But if you really want the function to be inlined it is better not to depend on this feature and just define the function in the header.
Q: Is there a way to force inlining for functions?
A: No
No matter how you designate a function as inline, it is a request that
the compiler is allowed to ignore: it might inline-expand some, all,
or none of the calls to an inline function.
Q: What are the inlining rules within C++ classes?
Inline member functions in C++
As far as Standard C++ is concerned, a inline function must be defined
in every translation unit in which it is used
...
This is different from non-inline functions which must be defined only
once in an entire program (one-definition-rule)...
For member-functions, if you define your function in the class, it is
implicitly inline. And because it appears in the header, the rule that
it has to be defined in every translation unit in which it is used is
automatically satisfied.
Here is a great FAQ (one that's more "practical" than "pedantic"):
http://www.parashift.com/c++-faq-lite/inline-functions.html
Is the first statement still true in modern C++, was it ever?
As David explained, there's the inline keyword as well. It can be ignored, as Paul stated.
Is there a way to force inlining for functions that are declared,
preferably in another file altogether?
Probably by configuring your compiler. It might be doing some inling behind your back anyway. Eg. gcc has -finline-functions etc. that will be switched on for certain optimisation levels
Is it generally better to keep short member functions inside class declaration block, or no?
Up to you. Be aware though that if you have an inline method used lots of times, then you can be increasing the size of your object files, and so potentially bloat the size of what you're building and maybe slow it down.
FWIW I only tend to put implementations in header files out of laziness :)