[英]Operator overloading, Rvalues, C++
考慮一個結構
template<typename T, size_t N>
struct Something {
std::array<T,N> args;
// Some constructors
};
現在讓我們為Something<T>
重載=
運算符。 事實上,我可以通過兩種方式實現它。
第一種方式
Something& operator=(const Something& rhs){
// an implementation with copy semantics
}
Something& operator=(Something&& rhs) {
// an implementation with move semantics
}
第二種方式
Something& operator=(Something rhs){
// implement with move semantics
}
所以,我的問題是什么是最標准的方式和最優化的方式來重載First Way或Second Way ?
對於這種特殊情況,您不應實現賦值運算符。 編譯器已經為您做到了:
#include <array>
#include <cstddef>
template<typename T, size_t N>
struct Something {
std::array<T,N> args;
};
int main() {
Something<int,42> a;
Something<int,42> b;
a = b;
}
對於一般情況,我建議您參閱運算符重載的基本規則和習語是什么? . 並考慮到並非所有東西都可以移動,也不是所有東西都可以復制。 而且,有時一個動作只是一個副本。 因此,這取決於。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.