c++ - 显式移动构造函数

标签 c++ c++11 constructor move-constructor c++14

尝试编译以下代码:

struct Foo
{
    explicit Foo ( void ) { }
    explicit Foo ( Foo&& rhs ) { }
};

Foo bar ( void )
{
    return Foo();
}

出现以下错误:

call to implicitly-deleted copy constructor of 'Foo'

很明显,copy-ctor 被隐式​​删除了。

问题 1: 为什么编译器需要 Foo 的拷贝函数?我希望 bar 的返回值是用 move-ctor 从右值 Foo() 构造的。

然后我将 move-ctor 重新声明为隐式的,一切都成功编译。

问题 2:为什么当我将 move-ctor 重新声明为隐式时编译器不再需要 copy-ctor?

问题 3:explicit 关键字在复制和移动 ctors 的上下文中意味着什么,因为它肯定与常规 ctors 的上下文不同。

最佳答案

这是因为返回值被认为是 implicit conversion .

引用自 C++11 标准:

6.6.3 The return statement

2 [...]

A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The value of the expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy or move of a temporary object (12.2). [...]

从返回表达式到保存返回值的临时对象的转换是隐式的。所以就像这会导致错误

Foo f = Foo();   // Copy initialization, which means implicit conversion

将代码作为您的示例也会触发类似的代码。


Question 1: Why does the compiler need the copy-ctor of Foo? I expected the return value of bar to be constructed from the rvalue Foo() with move-ctor.

因为上述原因,Foo(Foo&&) 不是可行的重载。规则规定,每当无法使用移动构造函数时,编译器就会考虑复制构造函数,在您的情况下,由于存在用户定义的移动构造函数,复制构造函数被隐式删除。

Question 2: Why the compiler does not need copy-ctor any more when I redeclare the move-ctor as implicit?

因为你的移动构造函数现在可以使用了。因此,编译器可以立即使用它,甚至无需考虑复制构造函数的存在。

Question 3: What does explicit keyword mean in the context of copy and move ctors as it definitely means something different from from the context of regular ctors.

恕我直言,这没有意义,只会导致问题,就像您的情况一样。

关于c++ - 显式移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872972/

相关文章:

c++ - 在 C++ 中使用 rand() 函数的正确方法是什么?

c++ - 如何正确实现与基类不同的版本?

c++ - 使用 boost-python 将参数从 Python 脚本传递到 C++

c++ - 有没有办法让 operator= 用于枚举?

c++ - 对象构造函数的静态库 "Undefined Reference"

c++ - C++ 中的数字证书解析库?

c++ - 警告 C4267 'initializing' : conversion from 'size_t' to 'DWORD' , 可能丢失数据

g++ 中的 C++11 语言支持,没有 `-std=c++11` 的库破坏功能

java - 如何区分类的两个实例

c++ - 构造函数中的奇怪行为