あなたのものが文字列のようにヒープに割り当てられたメモリを持つクラスであり、それが容量の概念を持っていたと想像してください。容量を幾何学的に増大させる演算子+=を指定します。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;
}
また、一度に2つ以上のものを追加したいとします。
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つの割り当て解除になっています。これは、より高速なコードに変換されます。