移動拷貝建構函式和移動賦值

2021-10-11 14:28:40 字數 1910 閱讀 7744

my_string(const char* str)

~my_string()

}my_string()

//預設的建構函式淺拷貝(不用delete的原因是object ob(ob1);一定分配好)

my_string(const my_string& str)

//語法沒錯,可能編譯會拋

buffer_ = new char[len_ + 1];

memset(buffer_, 0, len_ + 1);

memcpy(buffer_, str.data(), len_);

}//賦值建構函式

my_string& operator=(const my_string& str)

len_ = len;

this->buffer_ = new char[len_ + 1];

memset(buffer_, 0, len_ + 1);

memcpy(buffer_, str.data(), len_);

}return *this;

my_string( my_string&& str) noexcept

my_string& operator=(my_string&& str)noexcept

buffer_ = str.data();

len_ = str.get_len();

str.ret_null();

str.set_len(0);

}return *this;

}std::size_t get_len()const

char* data() const

void ret_null()

void set_len(int len)

#include

#include

//const my_string getperson()

////不能返回區域性變數的引用

//const my_string& getperson()

////所以臨時物件一定要std::move

const my_string getperson()

int main()

;//std::vectordest(src.size());

move_backward會執行移動賦值函式

//std::move_backward(src.begin(),src.end(),dest.end());

std::string str = 「1234567」;

std::string str1 = 「7895624」;

my_string mystr(str.c_str());

my_string mystr2(str1.c_str());

臨時物件

my_string mystr33(getperson());

一定賦值

mystr2 = std::move(mystr);

//臨時物件會執行移動建構函式

//my_string mystr44(std::move(my_string("123")));

//forward也會講乙個左值變右值

//my_string mystr55(std::forward(my_string("22222")));

//注意不會執行,移動建構函式

//它是乙個左值拷貝

//my_string mystr55(my_string("123"));

return 0;

}

總結:1:std::move函式就是左值轉右值(若右值的話,就不想轉)

2:std::forward函式就是左值轉右值,右值的話就不轉

3: move_backward會執行移動賦值函式

c 11 移動構造 移動賦值 拷貝構造

最近對準備深入學習一下c 11所有的新特性,今天研究了一下c 11的std move和std forward,在研究這個的時候,需要對c 0xx的拷貝構造,拷貝賦值有一些了解.這個不知道的自己去了解,這裡記錄一下c 11新加的移動版本 移動構造 移動賦值和拷貝構造 拷貝賦值的比較,文章引用 現代c ...

C 中的拷貝構造,賦值和移動構造

在說明這幾個名詞時,我們需要定義乙個測試類person,person類的測試環境為vs2013 一般情況下,在物件宣告時用拷貝建構函式對物件進行初始化 在編譯器進行優化的時候也會使用移動構造函 數 在有臨時物件產生的情況下 這樣效率會高一些,如避免深度拷貝之類的操作 一旦初始化之後,在 進行 運算將...

拷貝建構函式和移動建構函式解析

by gongzhihui 2017.12.5 拷貝構造函式呼叫時機 1.物件作為函式引數 2.物件作為函式返回值 3.用乙個物件初始化另乙個物件 t t1 t t2 ti t t3 t1 此處的 不是賦值運算子 拷貝賦值運算子 t t1 t t2 t1 t2 除了 類名 物件 物件 外的 應該都是...