私はC++で始まったばかりです。auto_mapというテンプレートクラスを作成する際にいくつかの問題があります。std :: mapは、オブジェクトではなくポインターを格納する必要があります。私はこのように使用std :: mapにポインタを格納するテンプレートクラスのコピーコンストラクタを書くには?
std::map<K*, V*, cmp> m;
::のような
何か
auto_map<std::string, std::string> t;
t.insert(new std::string("A"), new std::string("B"));
CPMは次のとおりです。
struct cmp
{
bool operator()(K *a, K *b) { return *a < *b; }
bool operator== (K *a) { return (*a); }
};
挿入する前に、すべての重複の挿入機能を検索:
void insert(K* k, V* v)
{
for (typename std::map<K*, V*, cmp>::iterator i=m.begin(); i!=m.end(); ++i)
{
if ((*k) == (*(*i).first))
{
delete (*i).first;
delete (*i).second;
m.erase(i);
}
}
m.insert(std::make_pair(k,v));
}
とコンストラクタ:
auto_map(){}
~auto_map()
{
for (typename std::map<K*, V*, cmp>::iterator i=m.begin(); i!=m.end(); ++i)
{
delete (*i).first;
delete (*i).second;
m.erase(i);
}
}
これらが正常に動作しているが、今、あなたは、おそらくアイデアを得ます。 ここで私はそれほど確実ではないという疑問があります。
どのようにコピーコンストラクタを書くのですか?
auto_map (auto_map& original)
{
for (typename std::map<K*, V*, cmp>::iterator i=original.m.begin(); i!=original.m.end(); ++i)
{
// what goes in here that will call each objects copy-constructor?
// how not to get complained about invalid conversions?...
// K newk = (*(*i).first);
// V newv = (*(*i).second);
// m.insert(std::make_pair(newk, newv));
// gives compiler error: cannot convert ‘const CntInteger’ to ‘CntInteger* const’ in initialization
// cannot convert ‘const CntInteger’ to ‘CntInteger*’ in initialization
}
};
お返事ありがとうございました!
なぜあなたはデフォルトのコンストラクタでそのループを持っていますか?確かに 'm'は空になりますか? –
私は彼がなぜこれをしたいのだろうと思っているのだろうか?ディープコピーセマンティクスを使用する場合は、オブジェクトへのポインタではなくオブジェクトを使用してください。あなたは通常の方法と同じだけ多くのコピーコンストラクタとコピー操作を行います。 std :: mapをレイヤー化する際に重大な間違いをしたことを心配する必要はありません。また、多くのオブジェクトを割り当てる必要がないため、処理速度が向上する可能性があります。オブジェクトのstd :: pairの割り当ては1つの割り当てです。ポインタのstd :: pairの割り当ては、std :: pairのための1つのallocとメンバーのための1つです。 –
ここであなたの本当のユースケースは何ですか? 'std :: string'はすでにメモリ管理されています。速度が心配な場合は、' std :: unordered_map 'を使うだけです。それはオプションですか? –