Consider the following C++ code.
struct foo { std::string value; }
inline foo bar() { return { "42" }; }
Now imagine I have a function that uses bar() in the following way.
std::string my_func()
{
const auto &x = bar();
return x.value;
}
Does this leak memory Because my_func only holds a reference to x? Or does x still get cleaned up after my_func terminates?
I know this is not how references are supposed to be used. But I just realized this compiles fine and wondered what the semantics of it are.
DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.
To answer your question in a more general way: the C++ standard does not require that references should occupy memory, but it does not require that they should not. The C++ compiler is free to compile the code in any way, as long as the results are correct, and what they are expected to be.
Causes of Memory LeaksUsing Unwanted Object Reference: These are the object references that are no longer needed. The garbage collector is failed to reclaim the memory because another object still refers to that unwanted object. Using Long-live Static Objects: Using static objects also leads to a memory leak.
Causes of Memory Leaks and Their Solutions One should not use static views while developing the application, as static views are never destroyed. One should never use the Context as static, because that context will be available through the life of the application, and will not be restricted to the particular activity.
But I just realized this compiles fine
Code provided should not compile, as trying to assign temporary to lvalue reference.
error: invalid initialization of non-const reference of type ‘foo&’ from an rvalue of type ‘foo’
If you fix code, by
std::string my_func()
{
const auto &x = bar();
return x.value;
}
then it would be fine, as const reference extends lifetime of temporary for lifetime of const reference.
Short answer: no.
Longer answer: In that case, the compiler will make sure, that the referenced temporary object will live to the end of the current scope. bar()
returns n object by value. That will be copied into a temporary, anonymous object and the reference will then reference that temporary object.
There are other situations similar to that, where the standard has this explicit requirement: temporaries that are bound to references live until the end of the current scope is reached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With