簡體   English   中英

在類對象上增強shared_ptr

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM