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

前端之家收集整理的这篇文章主要介绍了c – 复制构造函数隐式定义为已删除的情况前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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(){ }

反映这一点.但是,默认构造函数删除或无法访问的函数函数是什么?使用默认构造函数无法访问的函数有什么作用?你能举一个反映这个的例子吗?

解决方法

简单的说:
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.
原文链接:https://www.f2er.com/c/117836.html

猜你在找的C&C++相关文章