C++: lifetime of an object and external functions


Answers

What does the C++ standard mean regarding object lifetime begins?

12.6.2, [class.base.init], item 6, lists the steps of initialization, and this is the final one:

Finally, the compound-statement of the constructor body is executed.

So once the body has executed, initialization is complete.

Question

Let's suppose I want to call an external function of my object to perform some checks inside the body constructor. Since the lifetime of an object begins when the constructor's body finishes its execution, is it an unsafe design?

struct A;

void check(A const&) { /* */ }

struct A
{
    A() { check(*this); }
};

I mean, I'm calling and external function with a not-yet-alive object. Is it undefined behaviour?

Related questions: if I put that checking function as a member function (static or not), what does the standard says about using non-yet-alive objects outside the constructor but inside the class?

It there any difference in the lifetime concept between the point of view of a class and its users (a sort of in-class versus out-class lifetimes)?




when constructor body has finished running

This. An object that throws during construction is not guaranteed to have its invariants established, hence its lifetime doesn't start. A consequence of this is that the destructor will not get called:

#include <iostream>

struct Stillborn
{
    Stillborn()
    {
        std::cout << "inside constructor\n";
        throw 42;
    }

    ~Stillborn()
    {
        std::cout << "inside destructor\n";
    }
};

int main()
{
    try
    {
        Stillborn x;
    }
    catch (...)
    {
        std::cout << "inside catch block\n";
    }
}

live demo. Note how "inside destructor" does not appear in the output.




Links



Tags