7

我测试了以下代码:

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

我明白了

   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

但是,如果我用复制构造函数替换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

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

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

4

2 回答 2

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
于 2012-04-25T10:44:04.940 回答
3

它使用赋值运算符。

#include <iostream>
#include <vector>

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

    foo& operator= (const foo& other){
        std::cout << "assignment operator " << m_data << " " << other.m_data << 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;

    for(std::vector<foo>::const_iterator it = a.begin(); it != a.end(); ++it){
        std::cout << "a " << it->m_data << std::endl;
    }
    for(std::vector<foo>::const_iterator it = b.begin(); it != b.end(); ++it){
        std::cout << "b " << it->m_data << std::endl;
    }
    return 0;
}
parameterised constructor 3
copy constructor 3 3
copy constructor 3 3
copy constructor 3 3
parameterised constructor 4
copy constructor 4 4
copy constructor 4 4
copy constructor 4 4
a = b
assignment operator 3 4
assignment operator 3 4
assignment operator 3 4
a 3
a 3
a 3
b 4
b 4
b 4

有关原因,请参阅 Olis 的答案。

于 2012-04-25T10:44:10.000 回答