在lambda捕获的对象中选择移动构建器
作为测试,类定义了复制构造函数并显式删除了移动构造函数,以便无法移动构造对象。
struct foo {
foo()=default;
foo(const foo&) { std::cout << "foo copied\n"; }
foo(foo&&)=delete;
};
foo f;
foo a = f; // ok
foo b = move(f); // fails (expected)
据我了解,当显式删除移动构造函数时,其声明仍然存在于重载过程中,这就是无法构造 foo b 的原因。 仅定义复制构造函数时,不会声明移动构造函数,并且复制构造函数 const foo&
参数将接受右值。
但是,当我将对象放入 lambda 中时,它会编译:
foo f;
auto lmb = [f]() { }; // f copied into the closure object
auto x = std::move(lmb);
lambda 被转换为右值,但它所保存的对象仍然被复制(根据输出)。
(当定义 foo
move-constructor 时,它会按预期被调用)。
问题:为什么(已删除的) foo
move-constructor 没有被选中(因此无法编译)?
As a test, a class has the copy-constructor defined and the move-constructor explicitly deleted so that an object cannot be move-constructed.
struct foo {
foo()=default;
foo(const foo&) { std::cout << "foo copied\n"; }
foo(foo&&)=delete;
};
foo f;
foo a = f; // ok
foo b = move(f); // fails (expected)
It is my understanding that when a move-constructor is explicitly deleted, its declaration is still around for the overload process and that's why foo b
cannot be constructed.
With only the copy-constructor defined, the move-constructor would not be declared and the copy-constructor const foo&
argument would accept the rvalue.
However, when I put the object in a lambda, it compiles:
foo f;
auto lmb = [f]() { }; // f copied into the closure object
auto x = std::move(lmb);
The lambda is cast to an rvalue, but the object it holds is still copied (per the output).
(When the foo
move-constructor is defined, it is called, as expected).
Question: why is the (deleted) foo
move-constructor not selected (so that it fails to compile) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于Lambda的定义被默认而不是明确删除,因此对超载分辨率进行了调整以忽略它。
自C ++ 11以来,它将其硬编码为语言,并引入了移动语义。否则,在可用移动操作之前编写的较旧代码(并且本来可以隐式删除的移动操作)会在升级时默默分解。坏的。
Because the lambda's definition is defaulted and not explicitly deleted, therefore overload resolution is tuned to ignore it.
It's hard-coded into the language since C++11 and move semantics being introduced. Otherwise, older code that was written prior to move operations being available (and that would have had the move operations implicitly deleted) would silently break on upgrade. Bad.