c++ 之 std::move

原文鏈接:https://blog.csdn.net/p942005405/article/details/84644069

在C++11中,標準庫在中提供了一個有用的函數std::move,std::move並不能移動任何東西,它唯一的功能是將一個左值強制轉化爲右值引用,繼而可以通過右值引用使用該值,以用於移動語義。從實現上講,std::move基本等同於一個類型轉換:static_cast<T&&>(lvalue);

1、C++ 標準庫使用比如vector::push_back 等這類函數時,會對參數的對象進行復制,連數據也會複製.這就會造成對象內存的額外創建, 本來原意是想把參數push_back進去就行了,通過std::move,可以避免不必要的拷貝操作。
2、std::move是將對象的狀態或者所有權從一個對象轉移到另一個對象,只是轉移,沒有內存的搬遷或者內存拷貝所以可以提高利用效率,改善性能.。
3、對指針類型的標準庫對象並不需要這麼做.

用法:
原lvalue值被moved from之後值被轉移,所以爲空字符串.

//摘自https://zh.cppreference.com/w/cpp/utility/move
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;
    //調用常規的拷貝構造函數,新建字符數組,拷貝數據
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";
    //調用移動構造函數,掏空str,掏空後,最好不要使用str
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";
    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}

輸出:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章