I first declare a vector
of string
called test
. Then I push_back string
Hello
and World
and let a
be a reference
of test[0]
.And then I push_back a
into test
. However , I printed a
before and after push_back respectively and observed that a
became nothing after pushed into test
. Why a
becomes nothing? How does the vector work while pushing back a reference
(a)
of its element to itself ? Does that mean a
is no longer a reference
of test[0]
?
Thanks .
Remarks: If I push_back test[0]
, a
also becomes nothing. But test[0]
is still "Hello".
#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";
}
output:
1Hello
2
Update:
I got it ,thanks to answers and comments below. I printed the size
and capacity
of test
and observed that they are both 2
. When test.push_back(a)
is performed , the vector test
allocates new memory and copy its old elements to the new memory . Thus a
, the reference of it old elements , become undefined.
Here is the similar code using reserve
. I think the reason why a
becomes undefined is same as my original question. (Let me know if I'm wrong.)
#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";
}
output:
1Hello
size:2 capacity:2
2
test.push_back(a); //or : test.push_back(test[0]);
Adds a copy of a
as the last element of test
. The fact that a
is a reference to an element in test
is not relevant at all.
After that call, a
could be dangling reference. Using it as you have in the line
cout << "2"<< a << "\n";
is cause for undefined behavior.
test[0]
, on the other hand, returns a reference to the first element of test
. It could be a reference to a different object than what a
references.