Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of vector::push_back() elements

Tags:

c++

stl

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;
    }
}
like image 870
John Fitzpatrick Avatar asked Sep 16 '25 11:09

John Fitzpatrick


2 Answers

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).

like image 140
Alok Save Avatar answered Sep 18 '25 09:09

Alok Save


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.

like image 33
fredoverflow Avatar answered Sep 18 '25 09:09

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!