のコピーを作成しようとしない限り、unique_ptr
そのまま使用できます。の場合と同じように、ポインターの値を取得するには、反復子を「二重逆参照」する必要がありますshared_ptr
。簡単な例を次に示します。
#include <vector>
#include <memory>
#include <iostream>
template <class C>
void
display(const C& c)
{
std::cout << '{';
if (!c.empty())
std::cout << *c.front();
for (auto i = std::next(c.begin()); i != c.end(); ++i)
std::cout << ", " << **i;
std::cout << "}\n";
}
int main()
{
typedef std::unique_ptr<int> Ptr;
std::vector<Ptr> v;
for (int i = 1; i <= 5; ++i)
v.push_back(Ptr(new int(i)));
display(v);
for (auto i = v.begin(); i != v.end(); ++i)
**i += 2;
display(v);
}
あなたが(偶然に)そうするなら、のコピーを作成してunique_ptr
ください:
Ptr p = v[0];
その後、コンパイル時にわかります。実行時エラーは発生しません。あなたのユースケースは、container<unique_ptr<T>>
構築された理由です。動作するはずですが、動作しない場合は、実行時ではなくコンパイル時に問題が発生します。コンパイル時のエラーを理解していない場合は、ここで別の質問をしてください。