简体   繁体   English

为什么std :: promise :: set_value()有两个重载

[英]Why does std::promise::set_value() have two overloads

For the case when std::promise<> is instantiated with a non reference type, why does the set_value() method have two distinct overloads as opposed to one pass by value overload? 对于使用非引用类型实例化std::promise<>的情况,为什么set_value()方法具有两个不同的重载而不是一个值传递重载?

so instead of the following two 因此,而不是以下两个

std::promise::set_value(const Type& value);
std::promise::set_value(Type&& value);

just one 只有一个

std::promise::set_value(Type value);

This has at least the following two benefits 这至少具有以下两个好处

  1. Enable users to move the value into the promise/future when they want, since the API argument is a value type. 由于API参数是一种值类型,因此使用户能够在需要时将其值移动到promise / future中。 When copying is not supported it is obvious that the value is going to be copied. 当不支持复制时,很明显将要复制该值。 Further when the expression being passed into the function is a prvalue it can be completely elided easily by the compiler (especially so in C++17) 此外,当传递到函数中的表达式为prvalue时,编译器可以轻松地将其完全删除(尤其是在C ++ 17中)

  2. It conveys the point that the class requires a copy of the value a lot better and succinctly than two overloads which accomplish the same task. 它传达了这样一个观点,即类比完成同一任务的两个重载要好得多,而且要简洁得多。

I was making a similar API (as far as ownership is concerned) and I was wondering what benefits the design decision employed by the C++ standard library has as opposed to what I mentioned. 我正在制作一个类似的API(就所有权而言),我想知道C ++标准库采用的设计决策与我提到的相比有什么好处。

Thanks! 谢谢!

Passing an argument by value if it needs to be "transferred" unconditionally and then moving from it is a neat little trick, but it does incur at least one mandatory move. 如果需要无条件地“传递”值,则按值传递参数,然后再将其移走是一个巧妙的小技巧,但它确实会引起至少一个强制性的动作。 Therefore, this trick is best in leaf code that is used rarely or only in situations that are completely under the control of the author. 因此,此技巧是在很少使用或仅在完全受作者控制的情况下使用的叶代码中最好的方法。

By contrast, a core library whose users and uses are mostly unknown to the author should not unnecessarily add avoidable costs, and providing two separate reference parameter overloads is more efficient. 相反,作者和用户大多不了解其用户和使用的核心库不应不必要地增加可避免的成本,并且提供两个单独的参考参数重载更为有效。

In a nutshell, the more leaf and user you are, the more you should favour simplicity over micro-optimizations, and the more library you are, the more you should go out of your way to be general and efficient. 简而言之,您的叶子和用户越多,您越应该偏向于简化而不是微优化,而库越多,您就越应该走出通用和高效的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM