What does the C++ standard mean regarding object l

2019-03-03 17:39发布

In the n3690 C++ standard in section 3.8.1 there is this text:

The lifetime of an object of type T begins when:
— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.

Assume that there is a user defined constructor.

What does the last sentence mean? Is it when the initializer list has finished initializing or is it when constructor body has finished running? Or does the last sentence mean something else?

3条回答
你好瞎i
2楼-- · 2019-03-03 17:54

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.

查看更多
何必那么认真
3楼-- · 2019-03-03 18:05

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.

查看更多
爷的心禁止访问
4楼-- · 2019-03-03 18:11

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.

查看更多
登录 后发表回答