在lambda捕获的对象中选择移动构建器

发布于 2025-01-17 17:56:08 字数 714 浏览 0 评论 0原文

作为测试,类定义了复制构造函数并显式删除了移动构造函数,以便无法移动构造对象。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

命硬 2025-01-24 17:56:08

问题:为什么未选择(已删除的)foo move-constructor(因此无法编译)?

由于Lambda的定义被默认而不是明确删除,因此对超载分辨率进行了调整以忽略它。

[over.match.funcs.general]

8 成员函数([class.copy.ctor],[class.copy.assign])被定义为已删除的成员函数,在所有情况下都排除了一组候选函数。

自C ++ 11以来,它将其硬编码为语言,并引入了移动语义。否则,在可用移动操作之前编写的较旧代码(并且本来可以隐式删除的移动操作)会在升级时默默分解。坏的。

Question: why is the (deleted) foo move-constructor not selected (so that it fails to compile) ?

Because the lambda's definition is defaulted and not explicitly deleted, therefore overload resolution is tuned to ignore it.

[over.match.funcs.general]

8 A defaulted move special member function ([class.copy.ctor], [class.copy.assign]) that is defined as deleted is excluded from the set of candidate functions in all contexts.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文