gpt4 book ai didi

c++ - 复制构造函数隐式定义为已删除的情况

转载 作者:可可西里 更新时间:2023-11-01 18:35:42 26 4
gpt4 key购买 nike

N3797::12.8/11 [class.copy] 部分说:

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 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

第一种情况关于相应的复制/移动构造函数的歧义是很清楚的。我们可以这样写:

#include <iostream>
using namespace std;

struct A
{
A(){ }
A(volatile A&){ }
A(const A&, int a = 6){ }
};

struct U
{
U(){ };
A a;
};

U u;

U t = u;

int main(){ }

以反射(reflect)这一点。但是或者从默认构造函数中删除或无法访问的函数呢?无法从默认构造函数访问的函数有什么用?您能否提供一个反射(reflect)这一点的示例?

最佳答案

简单地说:

struct M { M(M const&) =delete; };
struct X { X(X const&) =default; M m; }; // X(X const&) is actually deleted!

隐式声明的函数也被认为是“默认的”([dcl.fct.def.default]/5);一个更熟悉的 C++11 之前的例子可能是这样的:

struct M { protected: M(M const&); };
struct X { M m; }; // X's implicit copy constructor is deleted!

请注意,如果您在函数声明后 显式默认该函数,如果该函数将被隐式删除,则程序格式错误 ([dcl.fct.def.default]/5) :

struct M { M(M const&) =delete; };
struct X { X(X const&); M m; };

X::X(X const&) =default; // Not allowed.

关于c++ - 复制构造函数隐式定义为已删除的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879937/

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