Lifetime of vector::push_back() elements
I want to confirm what I think I understand about the lifetime of objects which have been push_back()
'ed on an std::vector
. What I read says that the elements in the vector are copies. So, is the usage below OK? Specifically, is the variable s in f2()
a different instance of an std::string
than the one that is push_back()
'ed in f1()
, and thus safe to use?
void f1(std::vector<std::string>* pv) {
std::string s = "hi";
pv->push_back(s);
}
void f2(void) {
std::vector<std::string> v;
f1(&v);
for (size_t i = 0; i 开发者_开发百科< v.size(); ++i) {
std::string s = v.at(i);
std::cout << s;
}
}
Yes that is correct. A copy of string s
gets stored during push_back
. Check the doccumentation for detail. It states:
void push_back ( const T& x );
Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.
Parameters
x
Value to be copied to the new element.
T
is the first template parameter (the type of the elements stored in the vector).
std::string s = "hi";
pv->push_back(s);
Note that this is unnecessarily inefficient. Since s
is an lvalue, push_back
will indeed make a copy. If you say pv->push_back(std::string("hi"))
instead, a C++0x compiler can replace the copy with a move, because std::string("hi")
is an rvalue. You could even say:
pv->emplace_back("hi");
to construct the string object in place. No copy or move necessary.
When a push_back operation in the above, it does make a copy of string s
. So, it is safe.
Yes it is correct. The string s
will be copied.
However there is one interesting thing about how the class string is usually implemented that is valuable to mention. If you create a new string from another string or from a const char pointer it does not at first copy all the characters to its internal array, but uses a pointer to the source data. Only when you want to modify the string (or the source string is modified) an actual copy of characters array is created. So effectively string instances share characters data if it is not modified.
In case of your code, pushing back s
will copy an instance of string, but will not copy the characters "hi", so this will be relatively fast.
EDIT:
as others noted this copy-on-write string optimization is no longer common nowadays so nevermind ;) here's some information why this is the case
精彩评论