想象一下,你的东西是一个像字符串一样具有堆分配内存的类,并且它具有容量的概念。给它一个 operator+= 它将以几何方式增长容量。在 C++03 中,这可能看起来像:
#include <iostream>
#include <algorithm>
struct stuff
{
int size;
int cap;
stuff(int size_):size(size_)
{
cap = size;
if (cap > 0)
std::cout <<"allocating " << cap <<std::endl;
}
stuff(const stuff & g):size(g.size), cap(g.cap)
{
if (cap > 0)
std::cout <<"allocating " << cap <<std::endl;
}
~stuff()
{
if (cap > 0)
std::cout << "deallocating " << cap << '\n';
}
stuff& operator+=(const stuff& y)
{
if (cap < size+y.size)
{
if (cap > 0)
std::cout << "deallocating " << cap << '\n';
cap = std::max(2*cap, size+y.size);
std::cout <<"allocating " << cap <<std::endl;
}
size += y.size;
return *this;
}
};
stuff operator+(const stuff& lhs,const stuff& rhs)
{
stuff g(lhs.size + rhs.size);
return g;
}
还想象一下,您想一次添加的不仅仅是两个东西:
int main()
{
stuff a(11),b(9),c(7),d(5);
std::cout << "start addition\n\n";
stuff e = a+b+c+d;
std::cout << "\nend addition\n";
}
对我来说,这打印出来:
allocating 11
allocating 9
allocating 7
allocating 5
start addition
allocating 20
allocating 27
allocating 32
deallocating 27
deallocating 20
end addition
deallocating 32
deallocating 5
deallocating 7
deallocating 9
deallocating 11
我计算 3 个分配和 2 个释放来计算:
stuff e = a+b+c+d;
现在添加移动语义:
stuff(stuff&& g):size(g.size), cap(g.cap)
{
g.cap = 0;
g.size = 0;
}
...
stuff operator+(stuff&& lhs,const stuff& rhs)
{
return std::move(lhs += rhs);
}
再次运行我得到:
allocating 11
allocating 9
allocating 7
allocating 5
start addition
allocating 20
deallocating 20
allocating 40
end addition
deallocating 40
deallocating 5
deallocating 7
deallocating 9
deallocating 11
我现在减少到 2 个分配和 1 个释放。这转化为更快的代码。