Can you inline static member functions? - c++

I have a static member function which is merely syntactic sugar for me and I would like its body to appear in place of going through the motions of passing parameters to it. Will
inline static foo(int a) {return a & 0x00000040;}
be inlined just as it would if it was inline without being static?

The compiler chooses what it wants to do so we can't say what it will choose to do. That said, the function being static will not prevent it from being inlined; static functions are basically free functions with a different naming style and access to the class' private members.

A static member method has no this parameter, and can therefore only access static member variables.
It is distinct from whether the method is inlined or not. So the two are independent of each other.
The compiler decides if a method is going to be inlined or not. Your use of the keyword is merely a hint to the compiler.

Related

static functions compiler optimization C++

I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
To keep yourself from using this and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.
In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Static exists to associate a method with a class, rather than either:
Associating it with an instance of that class (like writing a normal, non-static member function).
Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
There is no optimization gain here.
Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.

Should I use static or inline?

I am writing a header-only library, and I can’t make up my mind between declaring the functions I provide to the user static or inline. Is there any reason why I should prefer one to the other in that case?
They both provide different functionalities.
There are two implications of using the inline keyword(§ 7.1.3/4):
It hints the compiler that substitution of function body at the point of call is preferable over the usual function call mechanism.
Even if the inline substitution is omitted, the other rules(especially w.r.t One Definition Rule) for inline are followed.
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)
Note: this answer is for C++. For C, see caf's answer. The two languages differ.
static has two relevant meanings:
For a function at namespace scope, static gives the function internal linkage, which in practical terms means that the name is not visible to the linker. static can also be used this way for data, but for data this usage was deprecated in C++03 (§D.2 in C++03 Annex D, normative). Still, constants have internal linkage by default (it's not a good idea to make that explicit, since the usage for data is deprecated).
For a function in a class, static removes the implicit this argument, so that the function can be called without an object of the class.
In a header one would usually not use internal linkage for functions, because one doesn't want a function to be duplicated in every compilation unit where the header is included.
A common convention is to instead use a nested namespace called detail, when one needs classes or functions that are not part of the public module interface, and wants to reduce the pollution the ordinary namespace (i.e., reduce the potential for name conflict). This convention is used by the Boost library. In the same way as with include guard symbols this convention signifies a lack of module support in current C++, where one is essentially reduced to simulating some crucial language features via conventions.
The word inline also has two relevant meanings:
For a function at namespace scope it tells the compiler that the definition of the function is intentionally provided in every compilation unit where it’s used. In practical terms this makes the linker ignore multiple definitions of the function, and makes it possible to define non-template functions in header files. There is no corresponding language feature for data, although templates can be used to simulate the inline effect for data.
It also, unfortunately, gives the compiler a strong hint that calls to the function should preferably be expanded “inline” in the machine code.
The first meaning is the only guaranteed meaning of inline.
In general, apply inline to every function definition in a header file. There is one exception, namely a function defined directly in a class definition. Such a function is automatically declared inline (i.e., you avoid linker protests without explicitly adding the word inline, so that one practical usage in this context is to apply inline to a function declaration within a class, to tell a reader that a definition of that function follows later in the header file).
So, while it appears that you are a bit confused about the meanings of static and inline – they're not interchangable! – you’re essentially right that static and inline are somehow connected. Moving a (free) function out of a class to namespace scope, you would change static → inline, and moving a function from namespace scope into a class, you would change inline → static. Although it isn’t a common thing to do, I have found it to be not uncommon while refactoring header-only code.
Summing up:
Use inline for every namespace scope function defined in a header. In particular, do use inline for a specialization of a function template, since function templates can only be fully specialized, and the full specialization is an ordinary function. Failure to apply inline to a function template specialization in a header file, will in general cause linking errors.
Use some special nested namespace e.g. called detail to avoid pollution with internal implementation detail names.
Use static for static class members.
Don't use static to make explicit that a constant has internal linkage, because this use of static is deprecated in C++03 (even though apparently the deprecation was removed in C++11).
Keep in mind that while inline can’t be applied to data, it is possible to achieve just about the same (in-practice) effect by using templates. But where you do need some big chunk of shared constant data, implemented in a header, I recommend producing a reference to the data via an inline function. It’s much easier to code up, and much easier to understand for a reader of the code. :-)
static and inline are orthogonal. In otherwords, you can have either or both or none. Each has its own separate uses which determine whether or not to use them.
If that function is not sharing the class state: static. To make a function static can benefit from being called at anywhere.
If the function is relatively small and clear: inline
(This answer is based on the C99 rules; your question is tagged with both C and C++, and the rules in C++ may well be different)
If you declare the function as just inline, then the definition of your function is an inline definition. The compiler is not required to use the inline definition for all calls to the function in the translation unit - it is allowed to assume that there is an external definition of the same function provided in another translation unit, and use that for some or all calls. In the case of a header-only library, there will not be such an external definition, so programs using it may fail at link time with a missing definition.
On the other hand, you may declare the function as both inline and static. In this case, the compiler must use the definition you have provided for all calls to the function in the translation unit, whether it actually inlines them or not. This is appropriate for a header-only library (although the compiler is likely to behave exactly the same for a function declared inline static as for one declared static only, in both cases inlining where it feels it would be beneficial, so in practice there is probably little to be gained over static only).

Inline Class Functions that have private data members

Now I have been learning about inline functions and I encountered something that really made me confused
See this class
class Nebla{
private:
int x;
public:
inline void set(int y){x=y;}
inline void print(){cout<<x<<endl;}
};
it has a private data member: int x;
And it has two public inline functions: set(int y) and print()
Now since they two functions are inline, when they are called the compiler replaces the function call with the contents of the function.
So if I do this
Nebla n;
n.set(1);
n.print();
since the two functions are inline, It should be the equivalent of this:
Nebla n;
n.x=1;
cout<<n.x<<endl;
but wait a second, x is private. Therefore, this shouldn't work.
But it does and I'm confused why it does work although normally you cant access private members from outside the class?
Can anyone explain to be why you can access private data members from outside the class but when a member function is inline it can although inline just replaces the function call with the contents of the function?
Data member protection is purely conceptual. It exists only at the compiler level. It is checked and enforced when the compiler translates the source code. Once the code is compiled, there's no difference between public and private data members anymore, i.e. there are no physical mechanisms that would enforce access control and prevent access to private data members.
Member access is enforced by the compiler in accordance with the language specification. The language specification states that class member functions (regardless of whether they are inline or not) have access to private members of the class. So the compiler allows that access. Meanwhile, other functions are prohibited such access, so the compiler complains about it.
In your example you are accessing private data member from a member function. That is allowed, so the code compiles, i.e. the compiler does not complain. What happens later in the generated machine code, after the function gets inlined, is completely irrelevant. That's all there is to it.
You misunderstand how inline works. The compiler inlines the logic of the code, not the actual text of the code.
Can anyone explain to be why you can access private data members from outside the class but when a member function is inline it can although inline just replaces the function call with the contents of the function?
Because the contents of the function are the contents of the function. They don't stop being the function just because they've been inlined. You are allowed to access private member variables from inside a member function. When a member function is inlined, its code is still inside the member function because the function is inlined.
First of all, whether or not it gets inlined is up to the compiler. In a lot of cases it will decide is not the best thing to do.
Second, in the case it does inline it, it does so with a compiled binary, product of the behavior described in the C++ source code, not the actual text.
Morbo says the inline keyword doesn't work that way.
Morbo says that the inline keyword says that symbol conflict at linker time involving this function should be ignored, and that all functions whose implementation is within the declaration of the class are implicitly inline.
Morbo is wise. You should listen to Morbo, even if there is a minor technical additional meaning of inline that involves taking addresses.
More seriously, inline just let's you put definitions of the implementation into a header file. Actually making the code inline is thus easier because it doesn't have to happen at link time (and most C++ linkers are too lazy) but it does not cause the code to be inline.
And finally privacy is conceptual, it is not enforced by the C++ run time. It is just enforced at compile time by telling you that something is out of bounds.

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.

'static' for c++ class member functions?

Why is the static keyword necessary at all?
Why can't the compiler infer whether it's 'static' or not?
As follows:
Can I compile this function without access to non-static member data? Yes -> static funcion.
No -> non-static function.
Is there any reason this isn't inferred?
If you expect the compiler to decide on the spot whether it's static or not, how does that affect external source files linking against the header file that just defines the method signatures?
The propery of being static or non-static affects the function type. Non-static member functions have an implicit this parameter, while static ones don't, for one example.
In other words, there's a major qualitative difference between static and non-static member functions. The compiler cannot "infer" this. This is a matter of the author's intent.
If I want (and need) my function to be non-static, I make it non-static, even if it doesn't access any non-static members of the class. If the compiler suddently decides to make my non-static function static just because it doesn't access any non-static members of the class, in general case it will destroy the functionality of the code.
Yes the compiler could, but it has no knowledge of your intent. And the original designers probably thought that supplying your intent was important.
Having redundancy in like this in the language helps to insure that many programmer errors will end up being caught by the compiler.
Another reason: If the function is static, it can't be overridden in derived classes. No polymorphism.