代码之家  ›  专栏  ›  技术社区  ›  Roman Starkov

C++变量声明和初始化规则

  •  3
  • Roman Starkov  · 技术社区  · 14 年前

    考虑以下声明和初始化类型为的变量的方法 C :

    C c1;
    
    C c2;
    c2 = C();
    
    C c3(C());
    
    C c4 = C();
    

    C级 ? (假设它有公共的默认构造函数和复制构造函数)。

    1 回复  |  直到 14 年前
        1
  •  10
  •   anon anon    14 年前

    这意味着:

    C c1;   // default constructor
    
    C c2;   // default constructor
    c2 = C(); // default constructor followed by assignment
    
    C c3(C());   // default constructor possibly followed by copy constructor
    
    C c4 = C();  // default constructor possibly followed by copy constructor
    

    注意编译器可以省略复制构造函数调用。它们相等吗?-好吧,这取决于复制构造函数和赋值运算符的作用。