ampawd ampawd - 3 months ago 16
C++ Question

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 ?

Answer

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;
    }
};
Comments