Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any situation in which an object's storage might change during its lifetime?

I've always assumed that an object begins and ends its lifetime in the same memory location, but I've recently come across a scenario where I need to be sure. Specifically, I'm looking for a guarantee from the standard that no matter what optimizations the compiler performs the address an object is constructed at is the same one that it will have its destructor called from... and that its destructor is, indeed, guaranteed to be called from that location unless the program is terminating.

I've always taken this stuff for granted, but upon closer examination I can't find a guarantee, and there's some language around copy and move elision that I'm not sure how to interpret. I'm hoping that some of the more standards-conversant people here can point me to chapter and verse.

like image 781
Reid Rankin Avatar asked Aug 15 '19 20:08

Reid Rankin


People also ask

What is the lifetime of an object?

In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction.

What is lifetime of local object in C++?

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


1 Answers

What you are looking for is defined in [intro.object]/1

[...] An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime, and in its period of destruction ([class.cdtor]).

This means the address cannot change as long as you can access it.

like image 195
NathanOliver Avatar answered Sep 27 '22 17:09

NathanOliver