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

*爱你&永不变心* 提交于 2019-12-02 09:38:35

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.

There is a note:

"[ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ]"

It means when the trivial constructor will finish its execution.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!