Reputation: 27455
What is the variable's "storage location"? One is using in the following chunk of the Standard:
If a program ends the lifetime of an object of type T with static (3.7.1), thread (3.7.2), or automatic (3.7.3) storage duration and if T has a non-trivial destructor,41 the program must ensure that an object of the original type occupies that same storage location when the implicit destructor call takes place; otherwise the behavior of the program is undefined.
Consider the following code:
#include <iostream>
using namespace std;
struct A
{
int a = 5;
A(){ cout << "A()" << endl; }
~A(){ cout << "~A()" << endl; }
};
struct B : A{ };
int main()
{
A a;
new (&a) B;
}
Does the storage location of original object changed at the line new (&a) B
? I know that at this line the lifetime of a
ends. How does end of the lifetime bound to the "changing of storage location"? I'm confused about these concepts.
Upvotes: 1
Views: 246
Reputation: 254741
What is the variable's "storage location"?
The region of memory used to store the object's data. This is fixed for the objects lifetime (optimisations might mean that the data is sometimes cached in registers or whatever; but the program must behave as if the object is at a fixed memory location throughout its lifetime).
Does the storage location of original object changed at the line
new (&a) B
?
No, the location of an object never changes. This creates a new object, of a different type, in the same memory location. In other words, it ends the lifetime of the original object - without calling its destructor - and reuses the memory for a different object.
The quote is saying that, since the variable has automatic storage duration, the destructor of A
will be called when it goes out of scope. This would be a very bad thing to do if there's no longer a valid A
object there; hence the rule that you must restore an A
before it's destroyed.
Upvotes: 1
Reputation: 141648
"storage location" is the section of memory (in the abstract machine -- in reality it could be RAM, cache, register, optimized out...) where the object is stored.
After an object's lifetime ends, it no longer exists, therefore it does not have a storage location. "changing of storage location" is not possible (and that text does not occur in your standard quote).
In this example, the storage location is the sizeof(int)
bytes starting at the memory address &a
. Initially it has an object called a
; and then it has a new object (also called a
).
Upvotes: 3