Lion Lion - 1 month ago 9
C++ Question

C++ reference to const with literal initialization

I'm diving a bit deeper into C++ and struggling with a reference to const which is initialized with an literal. e.g.

const int &r {100};


It definitly works but I'm wondering what the compiler makes with this kind of definition. Is there a real object created in the memory holding the value 100? Or is each occurance of
r
simply replaced by 100 in the code during compilation? This would be my guess because the initializer value couldn't either be changed nor referenced anyway during runtime, so why keep it in the memory?

Answer

Here:

const int &r {100};

a temporary int is being created and later is bound to r. Reference to const will prolong lifetime of temporary which is bound to it.

This is more usefull in cases like:

void foo (const std::string& s) {}    
foo("test"); // here temporary std::string is created and later on bound to `s`