을 수정, 내 수업이 내가있는 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();
}
벡터의 복사본을 만들고 있습니다. 대신 참조를 반환 :'표준 : : 벡터 <표준 : : shared_ptr의> & get_my_data()'그 @ 피터 –
내가 멤버 변수로 참조를 저장하려고 때문입니다 생각, 작동하지 않는 것 안에? b.get_my_data(). push_back() ... 등등. 그러나 제안 후에도 a_has_data_.push_back() 형식으로 작동하지 않습니다. – CptLightning
디자인을 다시 생각해 볼 수 있습니다. 두 클래스를 결합하거나 대신 데이터를 'A'에 저장하십시오. –