gpt4 book ai didi

c++ - 将成员变量保存为智能指针和显式定义析构函数的重要性

转载 作者:行者123 更新时间:2023-11-28 04:17:32 24 4
gpt4 key购买 nike

我有一个使用旧式 c++ 编写的代码,例如如下所示的原始指针(代码 1):

class Thing { 
private:
int data;
Thing* one;
Thing* second;
Thing* previous;
public:
Thing():one(0), second(0), previous(0) {}
// Here is my point of focus
~Thing() {
delete one;
delete second;
delete previous;
}
};

class Container {
private:
Thing* thing_ptr;
public:
Container() : thing_ptr(new Thing()) {}
void make_empty {
/*
Some algorithm for manually destroying the whole structure.
*/
}
~Container() {
delete thing_ptr;
}
};

我的目标是使用智能指针而不是原始指针并执行如下操作(代码 2):

class Thing { 
private:
int data;
std::shared_ptr<Thing> one;
std::shared_ptr<Thing> second;
std::shared_ptr<Thing> previous;
public:
Thing() : one(nullptr),
second(nullptr),
previous(nullptr) {}

// Here is my point of focus
~Thing() {
// Do some stuff
}
};

class Container {
private:
std::shared_ptr<Thing> thing_ptr;
public:
Container(): thing_ptr(nullptr) {}
void make_empty {
/*
Some recursive algorithm for manually destroying the whole structure.
*/
}
/* Some other functions */
~Container() {
// Do some stuff
}
};

案例 1. 如果我不提供适当的析构函数,编译器如何删除保存在共享指针中的指针?删除过程是否包含来 self 的类​​的任何析构函数调用?

情况 2. 如果没有明确定义的析构函数,并且有一些其他的 shared_ptr 成员变量在类 Thing 中保存类 Field 的对象,如下所示:

class Field {...}

class Thing {
private:
int data;
std::shared_ptr<Field> field;
std::shared_ptr<Thing> one;
std::shared_ptr<Thing> second;
std::shared_ptr<Thing> previous;
public:
Thing() : field(nullptr)
one(nullptr),
second(nullptr),
previous(nullptr) {}

// Here is my point of focus
~Thing() {
// Do some stuff
}
};

Field 的析构函数会被调用吗?如果不是,那么编译器如何决定如何正确删除这些东西?有缺点吗?

最佳答案

成员变量的析构函数在析构函数的内容之后自动调用。以相反的构造顺序调用构造函数。

此外,您应该使用 unique_ptr 而不是 shared_ptr。 shared_ptr 执行您几乎肯定不需要的引用计数。

关于c++ - 将成员变量保存为智能指针和显式定义析构函数的重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56283994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com