[英]Why I should not provide a forward and move versions for my types?
I've used std::swap
, std::move
and std::forward
but I've been recommended not to overload the latter two ones because they already have paramters that can hold any tylpe of value for example a forearding reference.我使用了
std::swap
、 std::move
和std::forward
但我被建议不要重载后两个,因为它们已经具有可以保存任何类型值的参数,例如前向引用。 So I should fully-quallify the call to those two functions:所以我应该完全限定对这两个函数的调用:
std::move(x);
std::forward<T&&>(x);
And I've read that I can provide my own version of swap
and thus I only add a usung declaration for the standard library one then call swap
without qualifying it (unqualified lookup):而且我已经读到我可以提供我自己的
swap
版本,因此我只为标准库添加一个 usung 声明,然后调用swap
而不对其进行限定(非限定查找):
using std::swap;// in case my class doesn't provide a swap version
swap(x, y); // where x, y are of class type. so don't use std::swap directly
So why I should not provide a version of std::move
and std::forward
for my types too?那么为什么我不应该为我的类型提供
std::move
和std::forward
版本呢?
Does this mean if I provided versions, there is no benefit because the library's are better like proving a sort function whereas the library's is so far better?这是否意味着如果我提供版本,则没有任何好处,因为库更好地证明了排序 function 而库的更好?
You are only allowed to provide specializations of std
functions when the standard permits you to.只有在标准允许时,您才可以提供
std
函数的特化。 No such permission is given for std::move
or std::forward
.没有为
std::move
或std::forward
提供此类许可。 Doing so makes your program ill-formed, no diagnostic required.这样做会使您的程序格式错误,不需要诊断。
std::swap
you should only specialize (not overload.) when the default implementation has efficiency problems: The default implementation is a basically: std::swap
你应该只在默认实现存在效率问题时专门化(而不是重载。):默认实现基本上是:
void std::swap( T& lhs, T& rhs ) {
auto tmp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(tmp);
}
The most common case is when your type needs to allocate memory when it is "empty".最常见的情况是当您的类型为“空”时需要分配 memory。 A more efficient swap could avoid such an allocation.
更有效的交换可以避免这种分配。
But for most types, this isn't a problem.但对于大多数类型,这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.