一意のオブジェクトをベクトルに生成する次の例があります。
#include <iostream>
#include <vector>
#include <algorithm>
int v=0;
struct A
{
A() : refValue( v++)
{ std::cout<<"constructor refValue="<<refValue<<std::endl; }
A( const A &r ) : refValue(r.refValue)
{ std::cout<<"copy constructor refValue="<<refValue<<std::endl; }
A& operator=( const A &r )
{
refValue = r.refValue;
std::cout<<"operator= refValue="<<refValue<<std::endl;
return *this;
}
~A() { std::cout<<"destructor refValue="<<refValue<<std::endl; }
int refValue;
};
A GenerateUnique()
{
A unique;
return unique;
}
struct B
{
B( const int n) : v()
{
std::generate_n( std::back_inserter( v ), n, &GenerateUnique );
}
std::vector< A > v;
};
int main()
{
B b(3);
}
メインをこれに変更すると:
struct B
{
B( const int n) : v(n)
{
}
std::vector< A > v;
};
次に、タイプ A の 1 つのオブジェクトがすべてのベクター要素にコピーされます。
すべての一意のオブジェクトを持つベクトルを作成する方法はありますか (最初の例のように)?
より明確にするために:ベクトルを含むクラスがあります。このベクトルには、すべての一意のオブジェクトが含まれている必要があります (1 つのオブジェクトのコピーではありません)。そして、コンストラクターの本体ではなく、初期化リストで初期化したいと思います。