C ++ 11“不可移动”类型 [英] C++11 "Non-movable" type

查看:265
本文介绍了C ++ 11“不可移动”类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么C ++ 11删除的函数参与重载解析?

我有两个关于以下C ++ 11代码的问题:

I have two questions about the following C++11 code:

#include <iostream>

using namespace std;

struct A {
  A()  { cout << "Default c-tor" << endl; }
  A(const A&)  { cout << "Copy c-tor" << endl; }
  A(A&&) = delete;
};

A f()
{
 A a;
 return a;
}

int main()
{
  A b = f();
  return 0;
}



我使用gcc和clang得到以下编译错误

I get the following compile errors with gcc and clang

gcc-4.7.2(g ++ --std = c ++ 11 main.cpp):

gcc-4.7.2 (g++ --std=c++11 main.cpp):

main.cpp: In function ‘A f()’:
main.cpp:16:9: error: use of deleted function ‘A::A(A&&)’
main.cpp:8:2: error: declared here
main.cpp: In function ‘int main()’:
main.cpp:21:10: error: use of deleted function ‘A::A(A&&)’
main.cpp:8:2: error: declared here


$ b b

clang-3.0(clang ++ --std = c ++ 11 main.cpp):

clang-3.0 (clang++ --std=c++11 main.cpp):

main.cpp:19:4: error: call to deleted constructor of 'A'
        A b = f();
          ^   ~~~
main.cpp:8:2: note: function has been explicitly marked deleted here
        A(A&&) = delete;
        ^
1 error generated.




  • 如果move构造函数是明确删除?

  • 有人知道不可移动类型的任何用途吗?

  • 提前感谢。

    推荐答案

    A(A&&) = delete;
    

    声明并定义为 delete 声明它,并且不使它完全不存在。相反,它是类似(但不完全相同)声明它为空和私有。如下:

    Declaring and defining it as delete does still declare it, and does not make it completely non-existent. Rather, it's similar (but not identical) to declaring it empty and private. Like so:

    private: 
      A(A&&){}
    

    事实上,这是有时用于其他运算符 = delete 可用。
    同样,它在查找的意义上存在,但是调用它是不允许的,并且在C ++调用权限(几乎或所有情况下)在一切之后完成,例如重载解析,名称查找。

    In fact, that was the trick sometimes used for other operators before = delete was available. Again, it exists in the sense of lookup, but calling it is not ever allowed and in C++ calling permissions are (in almost or all cases) done after everything else, such as overload resolution, name lookup.

    标准实际上说(8.4.3)

    The standard actually say (8.4.3)


    删除的函数是隐式内联的。

    A deleted function is implicitly inline.

    并且有注意到(我发现)说删除的函数不应该参与名称查找。

    And there's noting (that I find) saying that deleted functions should not participate in name lookup.

    此外,从8.4.3


    隐式或显式引用已删除函数的程序
    除了声明之外,是不合格的。 [注意:这包括隐式或显式调用
    函数并形成一个指针或
    指向函数的成员的指针。它甚至适用于未被潜在评估的
    表达式中的引用。

    A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function. It applies even for references in expressions that are not potentially-evaluated.

    这篇关于C ++ 11“不可移动”类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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