在C++中,当对象的构造函数中引发异常时,销毁对象的成员变量

人气:1,020 发布:2022-10-16 标签: exception memory-leaks constructor destructor c++

问题描述

这个问题基于Scott Meyers在他的书《更有效的C++》中提供的一个例子。考虑以下类:

// 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)抛出异常,则永远不会调用类的析构函数,这会导致已经分配的profilePicture被泄漏。

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

推荐答案

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

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

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

544