假设您的东西像字符串一样有堆分配内存的类,并且它具有容量概念。为其提供一个运算符+=,以几何方式增加容量。在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个释放。这意味着代码更快。