【发布时间】:2016-12-14 19:28:48
【问题描述】:
假设我有以下代码:
controller.hpp
#include "testing.hpp"
#include <boost/shared_ptr.hpp>
class controller
{
public:
controller(void);
void test_func (void);
boost::shared_ptr <testing> _testing;
}
控制器.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;
}
我在这里为班级成员正确使用shared_ptr 吗? controller 类中的多个函数需要使用_testing 对象,并且我不希望每次指针超出范围时都调用testing 类的构造函数/解构函数。也许这是无法避免的,我开始意识到。
【问题讨论】:
-
我会使用
boost::make_shared而不是new。.get()对您的使用方式毫无意义。此外,main()中没有名为_testing的变量,因此无法编译。 -
好的。你说得对。我正在尝试将
_testing共享给controller类中的所有函数,而不是每次都调用它的构造函数。
标签: c++ class boost shared-ptr