C++构造函数抛出异常时销毁对象的成员变量

Destroying the member variables of an object when an exception is thrown in its constructor in C++

此问题基于 Scott Meyers 在其著作 "More Effective C++" 中提供的示例。考虑以下 class:

// A class to represent the profile of a user in a dating site for animal lovers.
class AnimalLoverProfile
{
public:
    AnimalLoverProfile(const string& name,
                       const string& profilePictureFileName = "",
                       const string& pictureOfPetFileName = "");
    ~AnimalLoverProfile();

private:
    string theName;
    Image * profilePicture;
    Image * pictureOfPet;
};

AnimalLoverProfile::AnimalLoverProfile(const string& name,
                                       const string& profilePictureFileName,
                                       const string& pictureOfPetFileName)
 : theName(name)
{
    if (profilePictureFileName != "")
    {
        profilePicture = new Image(profilePictureFileName);
    }

    if (pictureOfPetFileName != "")
    {
        pictureOfPet = new Image(pictureOfPetFileName); // Consider exception here!
    }
}

AnimalLoverProfile::~AnimalLoverProfile()
{
    delete profilePicture;
    delete pictureOfPet;
}

Scott 在他的书中解释说,如果在对象的构造函数中抛出异常,则永远不会调用该对象的析构函数,因为 C++ 无法销毁部分构造的对象。在上面的示例中,如果调用 new Image(pictureOfPetFileName) 抛出异常,则永远不会调用 class 的析构函数,这会导致已分配的 profilePicture 被泄漏。

他描述了很多处理这个问题的不同方法,但我感兴趣的是成员变量theName。如果构造函数中对new Image的任意一个调用抛出异常,这个成员变量不就泄露了吗? Scott 说它不会被泄露,因为它是一个非指针数据成员,但是如果 AnimalLoverProfile 的析构函数从未被调用,那么谁来破坏 theName?

永远不会调用 AnimalLoverProfile 的析构函数,因为该对象尚未构造,而 theName 的析构函数将被调用,因为该对象已正确构造(即使它是尚未完全构建的对象)。这里可以通过使用智能指针来避免任何内存泄漏:

::std::unique_ptr<Image> profilePicture;
::std::unique_ptr<Image> pictureOfPet;

在这种情况下,当new Image(pictureOfPetFileName)抛出时,profilePicture对象已经构造完成,这意味着它的析构函数将被调用,就像theName的析构函数一样打电话。

斯科特是对的。考虑 intialization steps 对于 class:

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

也就是说,在进入构造函数体之前,数据成员已经被初始化了。如果在构造函数体内抛出任何异常,class 的析构函数将不会被调用(因为构造函数尚未完成),但数据成员将通过它们的析构函数被销毁(即 std::string::~string() for theName), 因为它们的初始化已经完成。这就是为什么我们应该使用智能指针而不是原始指针来解决此类异常保证问题。

如果在构建过程中抛出异常,所有已经构建的子对象都会被销毁。见 [except.ctor]/3:

If the initialization or destruction of an object other than by delegating constructor is terminated by an exception, the destructor is invoked for each of the object's direct subobjects and, for a complete object, virtual base class subobjects, whose initialization has completed ([dcl.init]) and whose destructor has not yet begun execution, except that in the case of destruction, the variant members of a union-like class are not destroyed. The subobjects are destroyed in the reverse order of the completion of their construction. Such destruction is sequenced before entering a handler of the function-try-block of the constructor or destructor, if any.


注意,我刚发现连第一个初始化的variant成员也被销毁了,所以在构造函数里面,如果你改变了variant的active成员,anactivated成员不在的时候仍然会被销毁它的生命周期!

Scott says it would not be leaked because it is a non-pointer data member,

Scott Meyer 的意思是无论如何都会销毁所有数据成员,但不像 std::string 的析构函数完成所有清理工作,原始指针不会自动调用 delete 自身当它们被摧毁时。

but if the destructor of AnimalLoverProfile is never called, then who destroys theName?

所有创建的数据成员都会自动销毁,无论是 intstd::string 还是 Image*。这是编译器必须实现的 C++ 规则,否则异常在构造函数中几乎无法使用。