2016-12-14 8 views
0

Скажем, у меня есть следующий код:подталкивания shared_ptr на объект класса

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; 
} 

Am Я использую shared_ptr pro perly здесь для члена класса? Многим функциям класса controller необходимо использовать объект _testing, и я не хочу, чтобы конструктор/деконструктор классов testing вызывался каждый раз, когда указатель выходит из области видимости. Возможно, этого нельзя избежать, я начинаю понимать.

+1

Я бы использовал 'boost :: make_shared', а не' new'. '.get()' бессмысленно, как вы его использовали. Кроме того, в вашей 'main()' нет переменной с именем '_testing', поэтому она не будет компилироваться. –

+0

ОК. Ты прав. Я пытаюсь использовать '_testing' для всех функций в классе' controller', не называя его конструктором каждый раз. – xinthose

ответ

1

Объект тестирования создается в конструкторе контроллера и разрушается, когда он выходит из области действия.

Просто:

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! 
} 

[Изменено] Для того, чтобы соответствовать владельцу вопрос редактирует

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; 
} 

Над 'аутсайдер' взял указатель на controller::_testing. В test_func они оба имеют указатель на один и тот же объект. Несмотря на то, что контроллер создает объект тестирования, он не разрушается, когда контроллер уничтожается. Очень удобно, когда возникают подобные ситуации. Этот код можно вставить в один .cpp-файл. Спасибо @Dan Mašek за хедз-ап за make_shared