![](/img/trans.png)
[英]Are there any pitfalls to using std::move() in value-oriented property setter?
[英]Are there any pitfalls in using move() instead of std::move()?
當使用新的C ++ 11的std::move()
,我注意到,由於ADL,可以只編寫move()
,而不使用std::
namespace前綴。
使用move()
就好了? 有任何陷阱嗎? 使用std::move()
更好嗎?
示例可編譯代碼如下:
#include <iostream>
#include <utility>
#include <vector>
template <typename T>
void print(const char* const descr, const std::vector<T>& v) {
std::cout << descr << ": ";
for (const auto& x : v) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
int main() {
std::vector<int> v{11, 22, 33};
std::vector<int> w = move(v);
print("v", v);
print("w", w);
}
如果參數類型也在std
ADL將只在std
查找內容。
如果在另一個正在使用的命名空間中有另一個名為move
符號,則編譯器將不知道您的意思。 現在可能沒有,但未來的變化可能會帶來一個。
此外,始終使用std::
使人們以后更容易閱讀您的代碼。 這清楚地表明,它不是一個move
是你自己定義或包括來自其他庫。 如果他們之前沒有聽說過(相對較新的) std::move
,那就特別有用。
絕對使用std::move
! 只有在std
命名空間中定義了類型(由於ADL),它才能在沒有std::
情況下工作。 它不適用於任何其他類型,如整數類型或使用定義的類型。
例:
std::vector<int> v = {1,2,3};
std::vector<int> w = move(w); // will work due to ADL
int i1 = 4;
int i2 = move(i1); // ERROR
struct Foo {};
Foo x{};
Foo y = move(x); // ERROR
它與實用程序中定義的移動功能相同。 http://en.cppreference.com/w/cpp/utility/move但是對於是的代碼清晰度,您可以編寫std :: move
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.