2013-03-01 3 views
1

을 수정, 내 수업이 내가있는 shared_ptr 객체의 벡터로해야 할 몇 가지 데이터를 공유 할 싶어요.벡터, 함수에서 반환과 본질적으로

다음 코드로 간단하게 편집 할 수 있습니다.

개체 A에서 개체 B에서 초기화 된 데이터를보고 싶습니다. 그러나 A 메서드 내에서 push_back()을 시도하면 B의 shared_ptr 개체 벡터의 크기가 변경되지 않습니다. . (주석과 함께 줄에 "이것은 관심의 포인트입니다".)

나는이 기능을 얻기 위해 사용해야하거나, 내가 잘못된 궤도에 나는 무엇을 접근. (C++ newbie here)

#include <memory> 
#include <vector> 
#include <iostream> 
using std::cout; 
using std::endl; 
class DataClass { 
    public: 
     int i_; 
}; 
class B { 
    public: 
     // constructor: 
     B() : my_data_(std::vector<std::shared_ptr<DataClass> >()) { 
      my_data_.push_back(std::shared_ptr<DataClass> (new DataClass)); 
      my_data_.push_back(std::shared_ptr<DataClass> (new DataClass)); 
      my_data_[0]->i_ = 1; 
      my_data_[1]->i_ = 2; 
      cout<<my_data_.size()<<endl; 
     }; 

     // return the data 
     std::vector< std::shared_ptr<DataClass> > get_my_data() { 
      return my_data_; 
     }; 

     // check the data: 
     void CheckData() { 
      cout<<my_data_.size()<<endl; // This is the point of interest 
     }; 
     // member variable 
     std::vector< std::shared_ptr<DataClass> > my_data_; 
}; 
class A { 

    public: 
     void start() { 
      // begin interaction with B class: 
      B b; 

      // get the vector of data pointers: 
      a_has_data_ = b.get_my_data(); 

      // modify some of the data: 
      a_has_data_.push_back(std::shared_ptr<DataClass> (new DataClass)); 
      a_has_data_[2]->i_ = 42; 

      b.CheckData(); 
     }; 
    private: 
    std::vector< std::shared_ptr<DataClass> > a_has_data_; 

}; 
int main() { 
    A a; 
    a.start(); 
} 
+1

벡터의 복사본을 만들고 있습니다. 대신 참조를 반환 :'표준 : : 벡터 <표준 : : shared_ptr의 > & get_my_data()'그 @ 피터 –

+0

내가 멤버 변수로 참조를 저장하려고 때문입니다 생각, 작동하지 않는 것 안에? b.get_my_data(). push_back() ... 등등. 그러나 제안 후에도 a_has_data_.push_back() 형식으로 작동하지 않습니다. – CptLightning

+0

디자인을 다시 생각해 볼 수 있습니다. 두 클래스를 결합하거나 대신 데이터를 'A'에 저장하십시오. –

답변

3

벡터 사본을 반환합니다. 당신은 데이터에 대한 참조를 반환해야합니다 A했다

// return the data 
std::vector< std::shared_ptr<DataClass> >& get_my_data() 
{ 
     return my_data_; 
}; 

b의 벡터, 그것의 복사본이 아닌 액세스합니다.

+0

그게 작동하지 않는 것 같아, 내가 A에서 멤버 변수로 참조를 저장하려고하기 때문에 그런 것 같아? b.get_my_data(). push_back() ... 등등. 그러나 제안 후에도 a_has_data_.push_back() 형식으로 작동하지 않습니다. – CptLightning

+1

@CptLightning 그러면 'B'를 'A'의 데이터 멤버로 유지하고 벡터 데이터 멤버를 삭제할 수 있습니다. 문제는 당신이 A :: start()의 범위에있는'B'와'A :: a_has_data'라는 두 가지 일생을 다른 일생과 결합 시키려고한다는 것입니다. – juanchopanza

+0

오 예, 이제 생애의 충돌을 봅니다. Thanks – CptLightning

1
a_has_data_.push_back(std::shared_ptr<DataClass> (new DataClass)); 

반환 유형이 복사 일 경우 위의 진술은 a_has_data_을 수정합니다. 그리고 b.CheckData();에 실제로 b's 회원의 크기를 확인하고 있습니다.

는 벡터의 크기를 확인하기 위해 A의 멤버 함수를 소개하고 당신의 증가를 볼 수 있습니다.

std::vector< std::shared_ptr<DataClass> > get_my_data() 

에서 여기

0

는 값이 너무 새로운 개체가 만들어 값을 기준으로 수익률 받고 있습니다. 다음 구현을 참조하십시오. 포인터를 보내 문제를 해결합니다.

#include <tr1/memory> 
#include <vector> 
#include <iostream> 
using namespace std; 
using std::cout; 
using std::endl; 
class DataClass { 
    public: 
     int i_; 
}; 
class B { 
    public: 
     // constructor: 
     B() : my_data_(std::vector<tr1::shared_ptr<DataClass> >()) { 
      my_data_.push_back(tr1::shared_ptr<DataClass> (new DataClass)); 
      my_data_.push_back(tr1::shared_ptr<DataClass> (new DataClass)); 
      my_data_[0]->i_ = 1; 
      my_data_[1]->i_ = 2; 
     }; 

     // return the data 
     std::vector< tr1::shared_ptr<DataClass> >* get_my_data() { 
      return &my_data_; 
     }; 

     // check the data: 
     void CheckData() { 
      cout<<my_data_.size()<<endl; // This is the point of interest 
     }; 
     // member variable 
     std::vector< tr1::shared_ptr<DataClass> > my_data_; 
}; 
class A { 

    public: 
     void start() { 
      // begin interaction with B class: 
      B b; 

      // get the vector of data pointers: 
      a_has_data_ = b.get_my_data(); 

      // modify some of the data: 
      b.CheckData(); 
      a_has_data_->push_back(tr1::shared_ptr<DataClass> (new DataClass)); 
      (*a_has_data_)[2]->i_ = 42; 
      b.CheckData(); 
     }; 
    private: 
    std::vector< tr1::shared_ptr<DataClass> >* a_has_data_; 

}; 
int main() { 
    A a; 
    a.start(); 
} 

참고 : 구형 gcc를 사용하기 때문에 코드를 tr1/memory로 변경했습니다.

+0

'A :: start()'스코프를 빠져 나올 때,'A :: a_has_data_'는 매달린 포인터로 남아 있습니다. – juanchopanza

+0

그럼 소멸자를 써야합니다. 나는 그 포인터를 암시한다고 가정했다. – Krish

+0

소멸자는 아무 관계가 없다. A :: a_has_dataA 소멸자는 문제를 해결하지 못합니다. 그것은 무관하다. – juanchopanza

관련 문제