c++ - 在类对象上 boost shared_ptr

标签 c++ class boost shared-ptr

假设我有以下代码:

Controller .hpp

#include "testing.hpp"
#include <boost/shared_ptr.hpp>
class controller
{
    public:
        controller(void);
        void test_func (void);
        boost::shared_ptr <testing> _testing;
}

Controller .cpp

#include "controller.hpp"
controller::controller() {
    boost::shared_ptr <testing> _testing (new testing);
    std::cout << _testing->test_bool << std::endl;
}

void controller::test_func (void) {
    // how to use _testing object?
    std::cout << _testing->test_bool << std::endl;

    return;
}

int main (void) {
    controller _controller;    // constructor called
    test_func();
    return 0;
}

测试.hpp

class testing
{
    public:
        bool test_bool = true;
}

我在这里是否正确地为类(class)成员使用了 shared_ptrcontroller 类中的多个函数需要使用 _testing 对象,我不希望每次都调用 testing 类的构造函数/解构函数指针超出范围的时间。也许这是无法避免的,我开始意识到。

最佳答案

测试对象在 Controller 构造函数中构建,并在超出范围时销毁。

只是:

int main (void) {
    controller _controller;    // constructor called
    _controller.test_func(); 
    // destructor of controller called, because it go out of scope,
    // so testing destructor is called too because, there is no more
    // shared_ptr pointing to it!
}

[已编辑] 匹配问题所有者的编辑

关于c++ - 在类对象上 boost shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41150646/

相关文章:

c++ - 简单的 x86-64 C++ 内联汇编 "Hello World"示例

java - 为什么我不能在迭代器上调用特定的类方法?

c++ - ANN OPENCV 错误断言失败

css - 我可以将带有 '' <div class ='home-icon' 'html 的图片更改为链接中的图片吗?

php - Objective-C 默认参数值

c++ - 递归 boost::variant 类型不能用 "-std=c++11 -stdlib=libc++"编译

c++ - 使用 boost 异步发送和接收自定义数据包?

c++ - Boost序列化编译报错,一头雾水

c# - 以编程方式双击系统托盘图标 Windows xp/7

c++ - 为什么 unique-ptr 不检查基类是否可虚拟破坏?