Reputation: 2426
I recently decided to unclutter a header file which had a lot of definitions like so:
// api.h
template< typename T>
inline void func( T param )
{
// stuff here
}
so I thought of turning it into:
// api.h
#include "api_details.h"
template< typename T>
inline void func( T param )
{
return details::func( param );
}
// api_details.h
namespace details {
template< typename T>
inline void func( T param )
{
// stuff here
}
}
hoping that inline
wouldn't add a cost to the extra copy I'm performing.
although the answers in 'C++ do inline functions prevent copying?' seem to imply that no copying takes place, this question arises:
if inlining doesn't copy the function parameters, then wouldn't the following behave badly?
inline void change_value( int i ) {
i++;
}
...
int x=5;
change_value(x);
assert(x==5);
is it just the optimizer that decides where to copy or not, or does the standard say anything about that?
Upvotes: 2
Views: 380
Reputation: 4463
if inlining doesn't copy the function parameters, then wouldn't the following behave badly?
In case if you change parameter it will be copied. And it is unrelated on function being inline
or not.
is it just the optimizer that decides where to copy or not, or does the standard say anything about that?
Yes this is optimizer's task. Standard mentions only behaviour, not implementation(there some references regarding to implementation, but only few of them). And inline
itself doesn't guarantee that function will be inlined, and vice versa, optimizer may inilne functions that wasn't declared as inline
.
What really matters is that parameters that was passed by value will not be changed by function call. No matter declared it inline
or not, and no matter it is actually being inlined or not.
Given that nowadays compilers are often much smarter on optimization that people are, inline
usually means not "inline this function" but rather "this function may have multiply(but still identical!) definitions across translation units".
Upvotes: 11