thread_local std::unique_ptr release not calling destructor

北城余情 提交于 2019-12-25 02:44:07

问题


Why isn't the destructor called in 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;
}

Output:

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

I would expect:

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

Using gcc 4.9.1


回答1:


Replace ptr.release(); with ptr.reset();.



来源:https://stackoverflow.com/questions/25326325/thread-local-stdunique-ptr-release-not-calling-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!