代码之家  ›  专栏  ›  技术社区  ›  Finley

阐明我对复制初始化和直接初始化的见解

  •  1
  • Finley  · 技术社区  · 6 年前

    定义一个类如下:

    class A {
    public:
      A(): s("") {}                             //default constructor
      A(const char* pStr): s(pStr) {}           //constructor with parameter
      A(const A& a) : s(a.s) {}                 //copy constructor
      ~A() {}                                   //destructor
    private:
      std::string s;
    };
    

    下面的代码将执行直接初始化:

    A a1("Hello!");   //direct initialization by calling constructor with parameter
    A a2(a1);          //direct initialization by calling copy constructor
    

    以下内容将执行复制初始化:

    A a3 = a1;  
    A a4 = "Hello!";
    

    据我所知, A a4 = "Hello" 相当于:

    //create a temporary object first, then "copy" this temporary object into a4 by calling copy constructor    
    A temp("Hello!");    
    A a4(temp);
    

    那么 A a3 = a1 A a2(a1) ? 似乎他们都叫复制构造函数我上面的评论是否正确(没有编译器优化)

    1 回复  |  直到 6 年前
        1
  •  0
  •   songyuanyao    6 年前

    两者之间有区别 direct-initialization copy-initialization 以下内容:

    复制初始化的权限小于直接初始化:显式构造函数不转换构造函数,复制初始化不考虑显式构造函数。

    所以如果你做复制构造器 explicit 然后 A a3 = a1 不起作用;当 A a2(a1) 仍然工作正常。