Can you please tell me if such code is correct (according to standard):
struct array {
int data[4];
operator const int*() const { return data; }
};
void function(const int*) { ... }
function(array()); // is array data valid inside function?
Thank you
The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
Object lifetime is determined by the path of strong references that point from a root reference to an object.
C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
The lifetime of a variable is the time during which the variable stays in memory and is therefore accessible during program execution. The variables that are local to a method are created the moment the method is activated (exactly as formal parameters) and are destroyed when the activation of the method terminates.
Yes. The temporary object is valid until the end of the full expression in which it is created; that is, until after the function call returns.
I don't have my copy of the standard to hand, so I can't give the exact reference; but it's in 12.2 of the C++0x final draft.
Yes. Temporaries are valid until the end of the full expression in which they are created. Therefore the nameless array temporary would be valid until the call to function
returns, and so its data
member would be as well.
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