这个问题是基于 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
被泄露。
他描述了许多不同的方法来处理这个问题,但我感兴趣的是成员变量theName
。如果任一调用new Image
在构造函数中抛出异常,这个成员变量不会泄露吗? Scott 表示它不会被泄露,因为它是一个非指针数据成员,但如果AnimalLoverProfile
从未被调用,那么谁销毁theName
?
的析构函数AnimalLoverProfile
永远不会被调用,因为该对象尚未构造,而析构函数theName
将被调用,因为该对象已正确构造(即使它是尚未完全构造的对象的字段)。通过使用智能指针可以避免任何内存泄漏:
::std::unique_ptr<Image> profilePicture;
::std::unique_ptr<Image> pictureOfPet;
在这种情况下,当new Image(pictureOfPetFileName)
投掷,将profilePicture
对象已经被构造了,这意味着它的析构函数将被调用,就像theName
叫做。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)