说我有以下代码:
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;
}
testing.hpp
class testing
{
public:
bool test_bool = true;
}
我是否正确使用shared_ptr
作为班级成员?课程controller
中的多个功能需要使用_testing
对象,我不想要testing
课程&#39;每次指针超出范围时调用的构造函数/解构函数。也许这个不可能&#39;我应该避免,我开始意识到。
答案 0 :(得分:1)
测试对象在控制器构造函数中构造,并在超出范围时被破坏。
只需:
__consumer_offsets
[已编辑]与问题所有者编辑相匹配
答案 1 :(得分:1)
我冒昧地重写代码来演示共享指针的用法。通常使用它是因为一个对象可以同时在两个地方,四处移动,并且自动销毁。
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
class testing
{
public:
std::string str;
testing( const char* in ) : str( in ) { }
};
typedef boost::shared_ptr <testing> SP_testing;
class controller
{
public:
controller( const char* in );
void test_func ( );
SP_testing _testing;
};
controller::controller( const char* in )
:_testing( boost::make_shared< testing >( in ) )
{
std::cout << "controller constructor: \"" << _testing->str << '\"' << std::endl;
}
void controller::test_func (void) {
std::cout << "test_func: \"" << _testing->str << "\" - cnt: " << _testing.use_count( ) << std::endl;
}
int main (void)
{
//yet to be used shared pointer
SP_testing outsider;
{
//this will create an instance of testing.
controller _controller( "this is a test" ); // constructor called, prints
outsider= _controller._testing; //assign shared pointer
_controller.test_func( ); // test called, prints usage count.
}//leaving scope, _controller will be destroyed but the _testing it created will not
std::cout << "outsider: \"" << outsider->str << "\" - cnt: " << outsider.use_count( ) << std::endl;
//now testing will get destroyed.
return 0;
}
上面,'outsider'指向controller::_testing
。在test_func
,它们都有一个指向同一对象的指针。即使控制器创建了测试对象,它也不会在控制器被破坏时被破坏。当出现这种情况时非常方便。此代码可以粘贴到一个.cpp文件中。感谢@DanMašek领导make_shared