C ++ 11中删除的成员函数的确切语义是什么? [英] What's the exact semantics of deleted member functions in C++11?

查看:85
本文介绍了C ++ 11中删除的成员函数的确切语义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct A
{
    A();

    A(const A&);
    A& operator =(const A&);

    A(A&&) = delete;
    A& operator =(A&&) = delete;
};

struct B
{
    B();

    B(const B&);
    B& operator =(const B&);    
};

int main()
{
    A a;
    a = A(); // error C2280

    B b;
    b = B(); // OK
}

我的编译器是VC ++ 2013 RC.

My compiler is VC++ 2013 RC.

错误C2280:"A& A :: operator =(A&&)":尝试引用a 功能已删除

error C2280: 'A &A::operator =(A &&)' : attempting to reference a deleted function

我只是想知道为什么删除A& operator =(A&&)时编译器为什么不尝试A& operator =(const A&);?

I just wonder why the compiler doesn't try A& operator =(const A&); when A& operator =(A&&) is deleted?

此行为由C ++标准定义吗?

Is this behavior defined by the C++ standard?

推荐答案

a = A(); // error C2280

右侧的表达式是临时的,这意味着它将查找operator=(A&&)并看到将其删除.因此,错误.没有进一步的搜索.

The expression on the right is a temporary which means it will look for operator=(A&&) and sees it is deleted. Hence the error. There is no further search.

=delete 的意思是不要使用我,而是使用 next 最好的一个".而是说:在需要我时不要用我 —而是在野外独自一人."

=delete does not mean "don't use me, instead use next best one". It rather means, "don't use me when you need me — instead be alone in the wild."

这是另一个例子.如果我希望仅使用long创建并且仅没有其他类型的类X的实例(即使它转换为long!),那么我将class X声明为: /p>

Here is another example. If I want the instances of my class X to be created with only long and no other type (even if it converts into long!), then I would declare class X as:

struct X
{
     X(long arg); //ONLY long - NO int, short, char, double, etc!

     template<typename T>
     X(T) = delete;
};

X a(1);  //error - 1 is int 
X b(1L); //ok    - 1L is long

这意味着,重载解析是在编译器看到=delete部分—之前执行的.并因此导致错误,因为发现 selected 重载已删除.

That means, the overload resolution is performed before the compiler sees the =delete part — and thus results in an error because the selected overload is found deleted.

希望有帮助.

这篇关于C ++ 11中删除的成员函数的确切语义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆