Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ constant temporary lifetime

Tags:

c++

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

like image 865
Anycorn Avatar asked Jul 06 '10 20:07

Anycorn


People also ask

How can you extend the lifetime of an object?

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.

How is the lifetime of an object determined?

Object lifetime is determined by the path of strong references that point from a root reference to an object.

What is lifetime of local object in C++?

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."

What is the lifetime of local object?

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.


2 Answers

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.

like image 125
Mike Seymour Avatar answered Sep 22 '22 00:09

Mike Seymour


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.

like image 28
Tyler McHenry Avatar answered Sep 22 '22 00:09

Tyler McHenry