矢量推回澄清

vector push back clarifying

我无法弄清楚 push_back(const value_type& val) 究竟是如何工作的,在 docs 中它说 val

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

  1. 引用val时如何复制?

  2. 复制是否会调用 val 的复制构造函数?

这里到底发生了什么?

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

这运行没有错误, parts[0] 是对本地向量 values 的引用还是副本? 如果它是引用,它不应该至少给出一些警告,说明您正在访问和修改已释放堆栈的本地对象吗?

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

想想复制构造函数。 它通过引用获取参数,并且完美地执行复制。

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

Will that copying ever call the copy constructor of val ?

复制操作使用复制构造函数。

您实际上可以通过提供用户定义的构造函数来查看它是否被复制或移动。

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

你可以试试这个

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

我在调试和发布版本中都调用了复制 cons。