c++ - 在 C++ 中将智能指针放入类数据(作为类成员)的正确方法是什么?

标签 c++ shared-ptr smart-pointers class-members

假设我有一个类 Boda:

class Boda {
    ...
};

而且我在这个类中有一个成员 cydo 我想成为一个智能指针(也就是说,我希望它在类被销毁后立即自动释放)。

我正在使用 Boost 的智能指针,所以我写:

class Boda {
    boost::shared_ptr<int> cydo;
    public:
        Boda () {
            cydo = boost::shared_ptr<int>(new int(5));
        }
};

这是将智能指针作为类成员的正确用法吗?

谢谢,Boda Cydo。

最佳答案

class Boda {
    boost::shared_ptr<int> cydo;
    public:
        Boda () : cydo(new int(5)) {} 
};

不过,我不明白你为什么要包装一个 int ... :)

关于c++ - 在 C++ 中将智能指针放入类数据(作为类成员)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483085/

相关文章:

c++ - (如何)当 std::future 准备好时,我可以在 boost::asio::io_service 上获得回调吗?

c++ - 亚信 : usage of self shared pointer in the examples

c++ - 在不绕过共享语义的情况下通过引用传输 vector<shared_ptr<T>>

c++ - 将 smart_pointer 传递给构造函数与原始指针

c++ - 需要帮助创建 C++ 成员函数来表示 RTOS microcos III 的任务

c++ - 将 matlab 内联命令转换为不同的

C++ 重载 = 运算符

c++ - shared_ptr 现实生活中的用例

c++ - 初始化指向 vector 的指针 vector

c++ - std::vector 的不完整类型