alexpeits
alexpeits

Reputation: 877

Scope for containers in C++

Let's say I have something like the following piece of code:

int main() {
    vector< vector<int> > vecs;
    int n_vecs;
    cin >> n_vecs;
    for (int i = 0; i < n_vecs; i++) {
        int n_nums;
        cin >> n_nums;
        vector<int> tmp;
        for (int j = 0; i < n_nums; i++) {
            int num;
            cin >> num;
            tmp.push_back(num);
        }
        vecs.push_back(tmp);
    }
}

which populates a vector of vector<int>s gradually. From some testcases, I understand that after the for loops finish, the vector is constructed as expected. However, I can't understand why is that: shouldn't the tmp vector be out of scope after the outer for loop finishes? Does a copy of it get inserted into the vecs vector? (The same applies for maps)

Upvotes: 0

Views: 164

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Does a copy of it get inserted into the vecs vector?

Yes.

Upvotes: 0

Christian Hackl
Christian Hackl

Reputation: 27528

Yes, a copy is made. See documentation for push_back:

The new element is initialized as a copy of value

There are two overloads for the function. In your example, the void push_back( const T& value ) overload is chosen because you are passing a named object and have not applied std::move, hence the copy.

If you passed an unnamed object or applied std::move, then the other overload would be chosen, "stealing" the contents of tmp to initialise the new object at the end of the vecs vector.

But that doesn't even matter for your question. In either case, the fact that tmp's lifetime ends afterwards (because of its scope in the source code) is irrelevant. The vecs vector already contains and owns a new element, and what happens to tmp is none of its concerns.


Perhaps the most important thing to keep in mind is that C++ standard containers are designed so that you can use them as easily as plain ints. You can copy them, return them, pass them around and assign them, and the results will always be as expected. This is because C++ standard containers own their contents.

Upvotes: 1

Related Questions