c++ - thread_local std::unique_ptr 释放不调用析构函数

标签 c++ c++11 smart-pointers thread-local-storage

为什么不在this code中调用析构函数? :

#include <iostream>
#include <thread>
#include <memory>

class base {
    public:
        base() {
            std::cout << "base()" << std::endl;
        }
        virtual ~base() {
            std::cout << "~base()" << std::endl;
        }
        base(const base&) = delete;
        base(base&&) = delete;
        base& operator=(const base&) = delete;
        base& operator=(base&&) = delete;
};

class derived final : public base {
    public:
        derived() {
            std::cout << "derived()" << std::endl;
        }
        virtual ~derived() {
            std::cout << "~derived()" << std::endl;
        }
};


void foo() {
    static thread_local std::unique_ptr<base> ptr;
    if (!ptr) {
        std::cout << "new ptr:" << std::this_thread::get_id() << std::endl;
        ptr.reset(new derived());
    } else {
        std::cout << "release ptr:" << std::this_thread::get_id() << std::endl;
        ptr.release();  // I would expect the destructor to be called here?!
    }
}

void thread_main() {
    foo();
    foo();
}

int main()
{
    std::thread thread1(thread_main);
    thread1.join();
    return 0;
}

输出:

new ptr:140671459997440
base()
derived()
release ptr:140671459997440

我希望:

new ptr:140671459997440
base()
derived()
release ptr:140671459997440
~derived()
~base()

使用 gcc 4.9.1

最佳答案

ptr.release(); 替换为 ptr.reset();

关于c++ - thread_local std::unique_ptr 释放不调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25326325/

相关文章:

c++ - 原始 C++ 指针是一流对象吗?

c++ - 为什么我们在 LLVM 中为 Objective-C 编译器将 C++ 类型定义为 void(而 C++ 编译器可以看到 Objective-C 接口(interface))?

使用自己的线程运行的 C++11 packaged_task 需要一个 join() 才能获得 future

c++ - 侵入式_ptr : Why isn't a common base class provided?

c++11 - 带有 std::vector 智能指针的深拷贝构造函数

c++ - 使用fork的c++程序中的非阻塞系统调用

c++ - 如何在C++模板中调用静态数组的析构函数?

c++ - 空参数包的模板特化

c++ - 如何将整数字符串转换为二维整数 vector ?

c++ - 为什么 Glibmm/Gtkmm 不包括 Glib::RefPtr 的一元取消引用运算符 *?