模板类中私有weak_ptr的定义

Definition of private weak_ptr in template class

本文关键字:ptr 定义 weak      更新时间:2023-10-16


首先:我是C++新手,所以不要评判我。:)
我尝试在模板类中定义静态weak_ptr,以便在所有实例上使用它。
这是我的代码:

template <class T> class my_template : public my_class {
    protected:
        std::shared_ptr<T> sp;
        virtual bool init_impl() {
            sp = wp.lock();
            ...
            return true;
        }
    private:
        static std::weak_ptr<T> wp;
};

但是编译给了我一个错误:

.../my_template.hpp:7: undefined reference to 'my_template<my_class2>::wp'

谁能帮忙?我只是不明白。

只需添加相同的标头:

template<class T>
std::weak_ptr<T> my_template<T>::wp;

对我有用! :)

根据您的注释,您没有单独的.cpp文件可用于定义static变量的存储。 在这种情况下,您可以公开一个 static 方法,该方法在内部声明自己的static变量:

template <class T> class my_template : public my_class {
    protected:
        std::shared_ptr<T> sp;
        virtual bool init_impl() {
            sp = get_wp().lock();
            ...
            return true;
        }
    private:
        static std::weak_ptr<T>& get_wp()
        {
            static std::weak_ptr<T> wp;
            return wp;
        }
};

当变量在函数内部声明static时,当函数退出时,它不会超出范围,它会被保留以供后续函数调用使用。