ampawd
ampawd

Reputation: 1010

vector push back clarifying

I can't figure out how push_back(const value_type& val) exactly works, in docs it says about val that

val is Value to be copied (or moved) to the new element ...

  1. How it can be copied when it takes val by reference ?

  2. Will that copying ever call the copy constructor of val ?

and what's exactly happening here ?

#include <iostream>
#include <vector>    
using namespace std;    
struct x
{
    x(int v = 0) : v(v) {}
    int v;
};    
vector<vector<x>> parts;    
void fillParts()
{
    vector<x> values = { x(1), x(2), x(3) };
    parts.push_back(values);
}        
int main()
{
    fillParts();  
    parts[0][0].v = -123;
    cout << parts[0][0].v;    // -123
    return 0;
}

this runs with no erros, is parts[0] is a reference to local vector values or a copy ? if it is a reference shouldn't it at least give some warnings saying that your accessing and modifying local objects of freed stack ?

Upvotes: 0

Views: 127

Answers (2)

Yola
Yola

Reputation: 19093

You can try this

class A
{
public:
    A() {}
    A(const A&) { cout << "copy cons" << endl; }
    A& operator= (A &&) { cout << "move" << endl; };
    A& operator= (const A &) { cout << "copy" << endl; };
};
vector<A> parts;
void fillParts()
{
    A a;
    parts.push_back(a);
}
int main()
{
    fillParts();
    return 0;
}

I got copy cons called in both debug and release builds.

Upvotes: 0

Dean Seo
Dean Seo

Reputation: 5733

How it can be copied when it takes val by reference?

Think of a copy constructor. It takes parameter by reference, and it performs copying perfectly.

class Bar
{
public:
    Bar(const Bar & rhs); // by reference, to copy.
};

Will that copying ever call the copy constructor of val ?

Copy operation uses copy constructor.

You can actually see if it's copied, or moved by providing user-defined constructors.

struct x
{
public:
    x(const x & rhs)
    {
        // Some copy operation.
        std::cout << "Copied" << std::endl;
    }

    x(x && rhs)
    {
        // Some move operation.
        std::cout << "Moved" << std::endl;
    }
};

Upvotes: 3

Related Questions