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

前端 未结 3 1421
滥情空心
滥情空心 2021-01-27 11:40

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          


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-27 11:50

    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 
    
    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.

提交回复
热议问题