Bra_Hancock
Bra_Hancock
2017-07-28 03:36

C++ 复制构造函数形参必须是const吗?等3个问题

  • c++
  • vector
  • 复制构造函数

下例中,复制构造函数如果不加const会出错,error C2558: class 'Asdf' : no copy constructor available or copy constructor is declared 'explicit'。
(1)我传的asd1不是个临时对象,为什么需要const?
(2)看不出复制构造函数为什么效率比移动构造函数低。
(3)我想把对象本身加到vector中,但是不能以引用形式传?只能用指针?
用的是VS2010的编译器。
求大神详解。谢谢。

#include <iostream>
#include <vector>

using namespace std;

class Asdf
{
public:
    Asdf()
    {
        cout << "Constructor." << endl;
    }

    Asdf(Asdf & asdf1)                //(1)
    {
        cout << "Copy Constructor." << endl;
    }

    Asdf(Asdf && asdf1)           //(2)
    {
        cout << "Move Constructor." << endl;
    }
    int aa;
};

int main()
{
    /*
    vector<Asdf *> vector1;               //(3)
    Asdf * asd1 = new Asdf();
    asd1->aa = 9;
    vector1.push_back(asd1);
    asd1->aa = 10;
    cout << vector1[0]->aa << endl;
    */
    vector<Asdf> vector1;
    Asdf asd1;
    asd1.aa = 9;
    cout << &asd1 << endl;
    vector1.push_back(asd1);                      //(1)
    vector1.push_back(move(asd1));               //(2)
    asd1.aa = 10;
    cout << vector1[0].aa << endl;

    return 0;
}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答