c++ - 为什么我的 UniquePtr 实现会重复释放?

标签 c++ memory

当我运行这个程序时,我得到了双倍的自由来实现唯一的 ptr。知道为什么会这样吗?

#include <iostream>
#include <memory>
using namespace std;

template <class T>
class UniquePtr
{
public:
        UniquePtr(T* t = nullptr) : t_(t) {}
        UniquePtr(const UniquePtr&) = delete;
        UniquePtr& operator=(const UniquePtr& oth) = delete;
        UniquePtr(UniquePtr&& oth) {
                std::swap(t_, oth.t_);
        }
        UniquePtr& operator=(UniquePtr&& oth) {
                std::swap(t_, oth.t_);
                return *this;
        };
        ~UniquePtr() {
                delete t_;
        }

private:
        T* t_;
};

struct Obj {
        Obj(int x): x_(x) { cout << "new " << x_ << endl; }
        ~Obj() { cout << "delete " << x_ << endl; }
        int x_;
};


template <class UP>
void test(UP&&) {
        {
                UP ptr(new Obj(1));
        }
        {
                UP ptr(UP(new Obj(2)));
        }
        {
                auto lambda = []() {
                        UP ptr(new Obj(3));
                        return ptr;
                };
                UP ptr2(lambda());
        }
}
int main() {
        cout << "unique_ptr" << endl;
        test(unique_ptr<Obj>());
        cout << endl;

        cout << "UniquePtr" << endl;
        test(UniquePtr<Obj>());
        cout << endl;

        return 0;
}
unique_ptr
new 1
delete 1
new 2
delete 2
new 3
delete 3

UniquePtr
new 1
delete 1
new 2
delete 2
new 3
delete 3
delete 0
free(): double free detected in tcache 2
Aborted

最佳答案

t_ 在您的 move 构造函数中未初始化,因此 moved from 指针最终指向未初始化的指针并具有未定义的行为(这将在 moved from 对象破坏和 deletes 未初始化的指针)。你需要:

UniquePtr(UniquePtr&& oth)
: t_(nullptr)
{
    std::swap(t_, oth.t_);
}

或者可能更简单:

UniquePtr(UniquePtr&& oth)
: t_(std::exchange(oth.t_, nullptr)
{
}

关于c++ - 为什么我的 UniquePtr 实现会重复释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72825008/

相关文章:

android - 如何在 Honeycomb 中获取外部内存分配?

c++ - C++ 中的 'side-effect' 到底是什么?

c++ - SFML 网络 |通过 sf::Packets 发送包含其他对象的对象会导致空数据

c++ - 指向设备常量的 CUDA 指针

Python:减少字典的内存使用

c++ - 为什么这个 C++ 结构体占用 96 字节内存?

c++ - 二维可变大小数组 C++

c++ - 变量赋值和逗号运算符

c++ - 如何从MFC中的Dialog头文件访问静态变量

eclipse - 发布需要大于默认 JVM 堆的 Eclipse 插件的最佳策略/实践?