这种代码理论上会有双重自由,但为什么没有重复
This code are theoretically there will be a double free, but why no repetition
新Widget由两个智能指针管理器组成,这样就不会出现双自由的问题,但执行后不会出现
std::vector<std::shared_ptr<Widget>> processedWidget;
class Widget {
public:
void process();
};
void Widget::process() {
processedWidget.emplace_back(this);
}
int main() {
{
std::shared_ptr<Widget> w(new Widget);
w->process();
}
return 0;
}
双重删除是标准中未定义的行为。因此,它可能看起来工作,而隐藏一个灾难。这样的代码的正确方法是使用std::enable_shared_from_this
std::vector<std::shared_ptr<Widget>> processedWidget;
class Widget : private std::enable_shared_from_this<Widget> {
public:
void process();
};
void Widget::process() {
processedWidget.emplace_back(shared_from_this());
}
int main() {
{
std::shared_ptr<Widget> w(new Widget);
w->process();
}
return 0;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么成员函数地址离自由函数这么远?
- 为什么未调用自由函数作为构造函数中的参数传递
- 为什么命名空间内的自由功能模棱两可
- 为什么标准允许我在没有析构函数的情况下自由存储分配类
- 双重自由或腐败 - 为什么
- 为什么类成员函数使用相同名称阴影自由函数
- 为什么我们可以检测 SFINAE 中 operator() 的默认参数值的存在,而不是自由函数和 PMF 的默认参数值
- 为什么 std::bind1st 不适用于自由函数
- 为什么双重自由或腐败
- 为什么在运算符重载中会出现自由错误
- 为什么会出现这种双自由错误
- 为什么泛型编程设计更喜欢自由函数而不是成员函数
- 为什么自由函数指针总是指针类型,而成员函数指针实际上不是指针?
- 为什么字符串上的双自由运算符=
- 这种代码理论上会有双重自由,但为什么没有重复
- 为什么我更喜欢使用自由存储而不是堆
- 为什么编译器不会自动内联自由定义的函数?而是导致链接器错误