C++11 "Non-movable"类型

标签 c++ gcc c++11 clang move-semantics

<分区>

Possible Duplicate:
Why do C++11-deleted functions participate in overload resolution?

我对以下 C++11 代码有两个问题:

#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 得到以下编译错误

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

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 构造函数,编译器是否应该使用复制构造函数?
  • 有谁知道“不可 move ”类型的用途吗?

提前致谢。

最佳答案

A(A&&) = delete;

将其声明并定义为 delete 仍然会声明它,并且不会使其完全不存在。相反,它类似于(但不完全相同)将其声明为空的和私有(private)的。像这样:

private: 
  A(A&&){}

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

标准其实是说(8.4.3)

A deleted function is implicitly inline.

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

另外,从 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 "Non-movable"类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085553/

相关文章:

c++ - C++ 中的抽象矩阵类

c++ - DLIB C++ 对象检测示例训练真的很慢

c++ - 默认声明的属性? (状态设计模式)

GNU Make 版本之间的兼容性

c++ - Cygwin:使用asm标签编译cpp文件

c++ - 可以将 std::pairs 的 std::vector 转换为字节数组吗?

c++ - 分配一个我不想等于任何可能输入的变量是什么?

C 中的常量 : declaration separate from definition

c++ - 为什么在声明析构函数时必须声明复制和移动构造函数?

c++ - 将每种类型包装在模板类中的可变参数模板中