13.49
StrVec(StrVec&&) NOEXCEPT;
StrVec& operator=(StrVec&&) noexcept;
StrVec::StrVec(StrVec &&s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap)
{
s.elements = s.first_free = s.cap = nullptr;
}
StrVec& StrVec::operator = (StrVec &&rhs) noexcept
{
if (this != &rhs) {
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
rhs.elements = rhs.first_free = rhs.cap = nullptr;
}
return *this;
}
String(String &&) noexcept;
String& operator=(String&&) noexcept;
String::String(String &&s) noexcept : elements(s.elements), end(s.end)
{
s.elements = s.end = nullptr;
}
String& String::operator = (String &&rhs) noexcept
{
if (this != &rhs) {
free();
elements = rhs.elements;
end = rhs.end;
rhs.elements = rhs.end = nullptr;
}
return *this;
}
Message(Message &&m);
Message& operator=(Message&&);
Message::Message(Message &&m) : contents(std::move(m.contents))
{
move_Folders(&m);
}
Message& Message::operator= (Message &&rhs)
{
if (this != &rhs)
{
remove_from_Folders();
contents = std::move(rhs.contents);
move_Folders(&rhs);
}
std::cout << "Message members moved" << std::endl; // debug
return *this;
}
13.50
String baz()
{
String ret("world");
return ret; //1
}
String s5 = baz(); //2
13.51
这里会使用移动构造函数而不是拷贝构造函数。
13.52
hp=hp2; //hp2是左值,使用拷贝赋值
hp=std::move(hp2); //使用移动赋值
详细解释见p478
13.53
@pezy
#include <string>
class HasPtr {
public:
friend void swap(HasPtr&, HasPtr&);
HasPtr(const std::string &s = std::string());
HasPtr(const HasPtr &hp);
HasPtr(HasPtr &&p) noexcept;
HasPtr& operator=(HasPtr rhs);
//HasPtr& operator=(const HasPtr &rhs);
//HasPtr& operator=(HasPtr &&rhs) noexcept;
~HasPtr();
private:
std::string *ps;
int i;
};
#include <iostream>
inline void swap(HasPtr &lhs, HasPtr &rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
std::cout << "call swap" << std::endl;
}
HasPtr::HasPtr(const std::string &s) : ps(new std::string(s)), i(0)
{
std::cout << "call constructor" << std::endl;
}
HasPtr::HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i)
{
std::cout << "call copy constructor" << std::endl;
}
HasPtr::HasPtr(HasPtr &&p) noexcept : ps(p.ps), i(p.i)
{
p.ps = 0;
std::cout << "call move constructor" << std::endl;
}
HasPtr& HasPtr::operator=(HasPtr rhs)
{
swap(*this, rhs);
return *this;
}
HasPtr::~HasPtr()
{
std::cout << "call destructor" << std::endl;
delete ps;
}
int main()
{
return 0;
}
13.54
略
6702

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



