1. Implementing Move Semantics
①C++11 以前的push_back()的实现 只有一种
template<typename T>
class vector
{
public:
...
// insert a copy of elem:
void push_back (const T& elem);
...
};
也就是说,你只能为该函数传入一个左值
②C++11 之后 有了一个重载版本
template<typename T>
class vector
{
public:
...
// insert a copy of elem:
void push_back (const T& elem);
// insert elem, when the value of elem is no longer needed:
void push_back (T&& elem);
...
};
&& 我们可以称之为 右值引用
2.区别
①push_back(const T&)
不会修改传入的这个引用,这个函数将会在调用者仍然需要这个实参的时候被调用
②push_back(T&&)
这个会修改传入的引用,没有const 修饰,这个函数将会在调用者不需要这个实参的时候被调用
3. 使用拷贝构造函数
class string
{
private:
int len; // current number of characters
char* data; // dynamic array of characters
public:
// copy constructor: create a full copy of s:
string (const string& s) : len{s.len}
{
data = new char[len+1]; // new memory
memcpy(data, s.data, len+1);
}
...
};
可以看出,这里是进行了一次深拷贝,分配了新的内存
4.使用移动构造函数
class string {
private:
int len; // current number of characters
char* data; // dynamic array of characters
public:
...
// move constructor: initialize the new string
//from s (stealing the value):
string (string&& s): len{s.len},data{s.data}
{
// copy pointer to memory
s.data = nullptr; // release the memory for the value
s.len = 0; // and adjust number of characters accordingly
}
...
};
s.data = nullptr; 将s的字符串移动过来,(偷过来) s.len = 0;
len{s.len},data{s.data}
我们可以这样调用
std::string c = std::move(b);
5.规则
对于不存在移动构造的类来说,我们仍然可以使用coll.push_back(std::move(s));
以为比如一个接口,他对用户是透明的,你并不知道是否有移动构造,OK
那么如果有,就会去调用移动构造,如果没有就去调用拷贝构造
本文介绍了C++11中引入的移动语义,包括右值引用的概念及其在vector::push_back函数中的应用。通过对比拷贝构造函数和移动构造函数,展示了如何利用移动语义提高代码效率。
1218

被折叠的 条评论
为什么被折叠?



