今天我们来讲讲c++11中引入了两个新东西
1.move constructor(移动构造函数)
2.move assignment(移动赋值)
Rule of three现在变成了Rule of five(多了上面说的两个东东)
class rule_of_five
{
char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block
public:
rule_of_five(const char* arg)
: cstring(new char[std::strlen(arg)+1]) // allocate
{
std::strcpy(cstring, arg); // populate
}
~rule_of_five()
{
delete[] cstring; // deallocate
}
rule_of_five(const rule_of_five& other) // copy constructor
{
cstring = new char[std::strlen(other.cstring) + 1];
std::strcpy(cstring, other.cstring);
}
rule_of_five(rule_of_five&& other) : cstring(other.cstring) // move constructor
{
other.cstring = nullptr;
}
rule_of_five& operator=(const rule_of_five& other) // copy assignment
{
char* tmp_cstring = new char[std::strlen(other.cstring) + 1];
std::strcpy(tmp_cstring, other.cstring);
delete[] cstring;
cstring = tmp_cstring;
return *this;
}
rule_of_five& operator=(rule_of_five&& other) // move assignment
{
delete[] cstring;
cstring = other.cstring;
other.cstring = nullptr;
return *this;
}
那么新加入的移动赋值以及移动拷贝要怎么使用呢,直接看代码
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
std::string str = "Hello";
std::vector<std::string> v;
// uses the push_back(const T&) overload, which means
// we'll incur the cost of copying str
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
// uses the rvalue reference push_back(T&&) overload,
// which means no strings will copied; instead, the contents
// of str will be moved into the vector. This is less
// expensive, but also means str might now be empty.
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";
}
Output:
After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"
看完大概明白一点儿了,加上move之后,str对象里面的内容被"移动"到新的对象中并插入到数组之中了,同时str被清空了。这样一来省去了对象拷贝的过程。所以说在str对象不再使用的情况下,这种做法的效率更高一些!