Karim Tarabishy
Karim Tarabishy

Reputation: 1253

Temporary variables created when using const reference

I am making some matrix class and I was wondering when a temporary object is created it is local to the function right? so it should get out of scope when function return but I don't know why that don't happen in this case I can use it after the function have returned.

Here is an example, this is the constructor:

int *data;   //member of class
Matrix3(const int (&ar)[N*N])
{
    data = const_cast<int*>(ar);
}

and here is how I use it:

Matrix3 m = { {1,2,3,4,5,6,6,6,6} };

Now I can still access that object from the destructor through the data pointer is this normal? the temporary variable is created on the heap then?!

Upvotes: 2

Views: 115

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137770

The lifetime of a temporary ends at the semicolon of the statement or declaration that introduced it, not at the end of the function. (Otherwise, an innocuous loop could easily cause a stack overflow.)

If you use a reference to an object after its lifetime has ended (such as the array here), then you get undefined behavior. C++ does not keep track of dead objects in order to tell you when you are using one. You happen to find the information from the dead array. But something else could have reused the memory, or it could have been returned to the system and you could get a segfault.

Avoid dangling references and pointers. Do not suppose that if it works in a test-case, that it works in the field.

Upvotes: 2

Oleksiy
Oleksiy

Reputation: 39790

int *data; // is a member, so it goes out of scope when the object is destroyed

However, if you declared it in a function like this:

void someFunction() {

    int *data;


}

// pointer is lost now and is inaccessible 

Upvotes: 0

Neil Kirk
Neil Kirk

Reputation: 21763

After your line executes, the temporary array is destroyed and the data pointer becomes invalid.

Upvotes: 0

Related Questions