Destroying the member variables of an object when an exception is thrown in its constructor in C++(在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
的析构函数被调用一样。
这篇关于在C++中,当对象的构造函数中引发异常时,销毁对象的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在C++中,当对象的构造函数中引发异常时,销毁对象的成员变量


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07