2014-03-06 157 views
1

我一直在爲學校工作,我們必須創建一個客戶端類與4字符串,4 int和矢量(int)作爲最後一個參數。問題是,當我想要打印矢量的所有元素時,如果直接使用我的增變器,它將打印不存在。C++奇怪的行爲變異矢量

vector<int> v_int; 
vector<int>::iterator it_v_i; 
v_int.push_back(2); 
v_int.push_back(3); 
v_int.push_back(7); 
v_int.push_back(1); 

Client client("nom1", "prenom1", "adress1", "city1", "comment1", 1240967102, 44522, 5, 10, v_int); 

v_int = client.getIdResources(); 
for (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) { 
    cout << *it_v_i << ", "; 
} 

打印2,3,7,1如預期的,但下面的代碼

for (it_v_i = client.getIdResources().begin(); it_v_i != client.getIdResources().end(); it_v_i++) { 
    cout << *it_v_i << ", "; 
} 

打印未識別號碼(如3417664 ...),未識別號碼,7,1

我真的不明白爲什麼會這樣

編輯:

構造:

Client::Client(const string& name, const string& surname, const string& adress, const string& city, const string& comment, 
      const int& phoneNb, const int& postalCode, const int& termAppointment, const int& priority, const vector<int>& idResources) 
       : name(name), surname(surname), adress(adress), city(city), comment(comment), phoneNumber(phoneNb), 
       postalCode(postalCode), termAppointment(termAppointment), priority(priority), idResources(idResources) 

{ }

的Mutator:

std::vector<int> getIdResources() const{ return idResources; } 

回答

3

的問題是,在第二片斷2個臨時vector s的被用於獲得begin()end()迭代(假定聲明是std::vector<int> client.getIdResources()而不是std::vector<int>& client.getIdResources())。這意味着it_v_i指的是被破壞的std::vector的元素。當it_v_i被取消引用時,它會導致未定義的行爲。

要正確地創建第二個代碼段函數,需要將std::vector的引用返回client.getIdResources()。但是,返回對內部類成員的引用會引入其他問題,例如生命期問題。

+0

那麼這是否意味着第一種情況是唯一正確的方法呢? –

+0

@DadEapPurple,是或者修改'getIdResources()'返回'const std :: vector &'。 – hmjd