![](/img/trans.png)
[英]Object pointed by boost::shared_ptr in base class is never destroyed
[英]Boost shared_ptr on class object
说我有以下代码:
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
类的构造函数/反构造函数。 也许这无法避免,我开始意识到。
测试对象在控制器构造函数中构造,并在超出范围时被破坏。
只是:
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!
}
[编辑]匹配问题所有者的编辑
我已经自由地重写了代码,以演示共享指针的用法。 通常,使用它是为了使一个对象可以同时在两个地方移动,并且销毁是自动的。
#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;
}
在上方,“局外人”使用了一个指向controller::_testing
的指针。 在test_func
它们都具有指向同一对象的指针。 即使控制器创建测试对象,也不会在销毁控制器时销毁它。 当出现这种情况时,非常方便。 可以将此代码粘贴到一个.cpp文件中。 感谢@DanMašek在make_shared
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.