gpt4 book ai didi

c++ - 默认情况下总是创建复制构造函数吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:56 24 4
gpt4 key购买 nike

据我所知,直到今天,在创建新类时会创建四个默认的东西。 “默认构造函数”、“析构函数”、“复制构造函数”和“赋值运算符”。但是今天当我浏览一篇 C++ 文章时,它说可能存在默认情况下不创建复制构造函数的情况。

  1. 这是真的吗?
  2. 如果是,在什么情况下?
  3. 在那些情况下,该类的实例如何按值传递?

最佳答案

1) 是的,可能存在默认情况下不创建复制构造函数的情况。

2) 删除隐式声明的默认构造函数的条件在12.8 复制和移动类对象[class.copy]中列出:

12.8.7是关于其他特殊成员函数的声明如何影响隐式声明的拷贝构造函数。每当类声明复制构造函数、移动构造函数或移动赋值运算符时。如果它声明了其中任何一个,那么你就不会得到一个隐式声明的。

...

7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

12.8.11 是关于数据成员和基类如何影响隐式声明的复制构造函数。本质上,如果该类有任何不可复制的数据成员或基类,则隐式声明的复制构造函数是 deleted:

11 An implicitly-declared copy/move constructor is an inline public member of its class. A defaulted copy/ move constructor for a class X is defined as deleted (8.4.3) if X has:

— a variant member with a non-trivial corresponding constructor and X is a union-like class,

— a non-static data member of class type M (or array thereof) that cannot be copied/moved because overload resolution (13.3), as applied to M’s corresponding constructor, results in an ambiguity or a function that is deleted or inaccessible from the defaulted constructor,

— a direct or virtual base class B that cannot be copied/moved because overload resolution (13.3), as applied to B’s corresponding constructor, results in an ambiguity or a function that is deleted or inaccessible from the defaulted constructor,

— any direct or virtual base class or non-static data member of a type with a destructor that is deleted or inaccessible from the defaulted constructor,

— for the copy constructor, a non-static data member of rvalue reference type, or

...

3) 您可以声明和定义(通过提供实现或默认复制构造函数或移动复制构造函数,或两者兼而有之。

关于c++ - 默认情况下总是创建复制构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24237329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com