Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of object is over before destructor is called?

I don't understand this:

3.8/1 "The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or — the storage which the object occupies is reused or released."

If the lifetime ends before the destructor starts, doesn't that mean accessing members in the destructor is undefined behavior?

I saw this quote too:

12.7 "For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior."

But it doesn't make clear what's allowed during the destructor.

like image 819
Pubby Avatar asked Dec 23 '11 01:12

Pubby


People also ask

When a destructor is called after the end of object life?

2. When a destructor is called? Explanation: The destructor is called just before the object go out of scope or just before its life ends. This is done to ensure that all the resources reserved for the object are used and at last, are made free for others.

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.

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.

Which object's destructor will be called first?

The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called. Destructors for nonstatic members are called before destructors for base classes are called.


1 Answers

If the lifetime ends before the destructor starts, doesn't that mean accessing members in the destructor is undefined behavior?

Hopefully not:

From N3242 Construction and destruction [class.cdtor] /3

To form a pointer to (or access the value of) a direct non-static member of an object obj, the construction of obj shall have started and its destruction shall not have completed, otherwise the computation of the pointer value (or accessing the member value) results in undefined behavior.

like image 110
curiousguy Avatar answered Nov 10 '22 06:11

curiousguy