假设我有以下代码:
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_ptr
? controller
类中的多个函数需要使用 _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/