如果复制了容器,则在哪种情况下调用复制构造函数

Mic*_*ael 7 c++ constructor stl

我测试了以下代码:

#include <iostream>
#include <vector>

class foo {
public:
    int m_data;
    foo(int data) : m_data(data) {
        std::cout << "parameterised constructor" << std::endl;
    }
    foo(const foo &other) : m_data(other.m_data) {
        std::cout << "copy constructor" << std::endl;
    }
};

main (int argc, char *argv[]) {
    std::vector<foo> a(3, foo(3));
    std::vector<foo> b(4, foo(4));
    //std::vector<foo> b(3, foo(4));
    std::cout << "a = b" << std::endl;
    a = b;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我明白了

   parameterised constructor
   copy constructor
   copy constructor
   copy constructor
   parameterised constructor
   copy constructor
   copy constructor
   copy constructor
   copy constructor
   a = b
   copy constructor
   copy constructor
   copy constructor
   copy constructor
Run Code Online (Sandbox Code Playgroud)

但是,如果我std::vector<foo> b(4, foo(4));通过std::vector<foo> b(3, foo(4));复制构造函数替换未被调用a = b,则输出为

parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
Run Code Online (Sandbox Code Playgroud)

为什么在这种情况下没有调用复制构造函数?

我正在使用g ++(Ubuntu/Linaro 4.6.1-9ubuntu3)4.6.1

Oli*_*rth 12

在第一种情况下,a需要在分配时增长,这意味着必须重新分配所有元素(因此需要对其进行破坏和构造).

在第二种情况下,a不需要增长,因此使用赋值运算符.

http://ideone.com/atPt9 ; 添加一个打印消息的重载复制赋值运算符,我们得到以下第二个示例:

parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
copy assignment
copy assignment
copy assignment
Run Code Online (Sandbox Code Playgroud)