So I have the following code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> strs;
strs.push_back("happy");
const string& a1 = strs[0];
strs.push_back("birthday");
const string& a2 = strs[1];
strs.push_back("dude");
const string& a3 = strs[2];
printf("%s\n", a1.c_str());
return 0;
}
which is pretty straightforward but it doesn't work. The printf doesn't print anything. It does print if I change it to:
const string& a1 = strs[0].c_str();
can someone please explain the behavior of it.
Your calls to
push_back
potentially (and in your case obviously actually) invalidate all references into thevector
, namely if thevector
is too small to store the new element. You thus cannot use any references into thevector
created before apush_back
unless you make sure that thevector
s capacity is big enough.If you make sure that the
vector
has enough capacity for all the elements (i.e. by usingstd::vector::reserve
) before you create the references, your first version will work as expected.Your second example works because you create a new, temporary
string
(which has its lifetime extended to the lifetime of the reference) the reference binds to.