簡體   English   中英

向量如何在將元素的引用推回給自身的同時如何工作?

[英]How does vector work while pushing back a reference of its element to itself?

我首先聲明一個名為teststring vector 然后,我的push_back string HelloWorld ,讓areferencetest[0]而當時我的push_back a進入test 但是,我分別在push_back之前和之后打印a ,並且觀察到在推入test之后a變成了什么。 為什么a變成什么? 矢量如何在將元素的reference (a)推回到自身的同時工作? 這是否意味着a不再是test[0]reference
謝謝 。

備注:如果我push_back test[0]a也變得一無所獲。 但是test[0]仍然是“你好”。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
     vector<string> test;
     test.push_back("Hello");
     test.push_back("World");
     string& a = test[0];
     cout << "1"<< a << "\n";
     test.push_back(a);          //or : test.push_back(test[0]);
     cout << "2"<< a << "\n"; 
} 

現場演示

輸出:

1Hello
2

更新:

我得到了它,感謝下面的答案和評論。 我打印了testsizecapacity ,發現它們都是2 執行test.push_back(a) ,矢量test分配新內存並將其舊元素復制到新內存中。 因此a ,它舊元素的參考,是不確定的。

這是使用reserve的類似代碼。 我認為a變得不確定的原因與我原來的問題相同。 (如果我錯了,請告訴我。)

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
     vector<string> test;
     test.push_back("Hello");
     test.push_back("World");
     string& a = test[0];
     cout << "1"<< a << "\n";
     cout << "size:" << test.size() << " capacity:" <<test.capacity() <<"\n";  
     test.reserve(3);       
     cout << "2"<< a << "\n"; 
} 

輸出:

1Hello
size:2 capacity:2
2
test.push_back(a);          //or : test.push_back(test[0]);

添加的副本a作為最后一個元素test a是對test元素的引用這一事實根本不相關。

在那個電話之后, a可能是懸空參考。 按照你的方式使用它

 cout << "2"<< a << "\n"; 

導致未定義的行為。

另一方面, test[0]返回對第一個test元素的引用。 它可以是對引用的不同對象a引用。

由於vector::push_back根據std::vector定義使對容器的現有引用無效,因此string& a變為未定義。 請參見http://en.cppreference.com/w/cpp/container/vector/push_back

如果new size()大於capacity(),那么所有迭代器和引用(包括過去的迭代器)都將失效。 否則只有過去的結束迭代器無效。

既然你不知道什么是矢量的前推能力a是,你不能確定你參考並沒有失效; 這是未定義的行為,在某些情況下可能“有效”,但在其他情況下可以做任何事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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