gpt4 book ai didi

c++ - 按值或右值引用接受仅移动参数

转载 作者:IT老高 更新时间:2023-10-28 23:21:55 25 4
gpt4 key购买 nike

这篇文章的接受答案Pass by value vs pass by rvalue reference说:

For move-only types (as std::unique_ptr), pass-by-value seems to be the norm...

我对此有点怀疑。假设有一些不可复制的类型,Foo,移动起来也不便宜;还有一些类型 Bar 有一个成员 Foo

class Foo {
public:
Foo(const Foo&) = delete;
Foo(Foo&&) { /* quite some work */ }
...
};

class Bar {
public:
Bar(Foo f) : f_(std::move(f)) {} // (1)
Bar(Foo&& f) : f_(std::move(f)) {} // (2)
// Assuming only one of (1) and (2) exists at a time

private:
Foo f_;
};

那么对于下面的代码:

Foo f;
...
Bar bar(std::move(f));

构造函数 (1) 引发 2 个移动构造,而构造函数 (2) 仅引发 1 个。我还记得在 Scott Meyers 的 Effective Modern C++ 中阅读过关于此的内容,但不记得是哪一项。

所以我的问题是,对于仅移动类型(或更一般地说,当我们想要转移参数的所有权时),我们不应该更喜欢 pass-by-rvalue-reference 以获得更好的性能吗?

更新:我知道按值传递构造函数/赋值运算符(有时称为统一 ctors/赋值运算符)可以帮助消除重复代码。我应该说我对以下情况更感兴趣:(1) 性能很重要,(2) 类型不可复制,因此不存在接受 const lvalue 的重复 ctors/assignment 运算符引用参数。

更新 2: 所以我找到了 Scott Meyers 的关于具体问题的博客:http://scottmeyers.blogspot.com/2014/07/should-move-only-types-ever-be-passed.html .这篇博客讨论了他在Effective Modern C++的第 41 条中主张的原因:

Consider pass by value only for copyable parameters...that are cheap to move...[and] always copied.

在该项目中有一个关于按值传递与右值引用的广泛讨论,此处无法引用。关键是,这两种方式各有优缺点,但对于转移只移动对象的所有权,通过右值引用传递似乎更可取。

最佳答案

在这种情况下,我们可以吃蛋糕。只为类 Foo 引用启用的模板构造函数为我们提供了完美的转发以及构造函数的单个实现:

#include <iostream>
#include <utility>

class Foo {
public:
Foo() {}
Foo(const Foo&) = delete;
Foo(Foo&&) { /* quite some work */ }
};

class Bar {
public:
template<class T, std::enable_if_t<std::is_same<std::decay_t<T>, Foo>::value>* = nullptr>
Bar(T&& f) : f_(std::forward<T>(f)) {} // (2)
// Assuming only one of (1) and (2) exists at a time

private:
Foo f_;
};

int main()
{
Foo f;
Bar bar(std::move(f));

// this won't compile
// Foo f2;
// Bar bar2(f2);

}

关于c++ - 按值或右值引用接受仅移动参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38140495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com