0

std::vector に auto_ptr(s) へのポインタを格納できますか? 安全ですか?

XML ファイルを読み取り、auto_ptr を使用してそれぞれのオブジェクトを作成するフォルダーを列挙します。XML ファイルの数が事前にわからないので、ベクトルを使用して基本的にそれらへのポインターのリストを保持したいと考えています。

また、ポインターがベクターから削除される (またはベクターが破棄される) と、ポインターはほとんどなくなっていると想定しているため、ポインターを NULL に設定することを心配する必要はありません。

4

2 に答える 2

4

You can't store an auto_ptr itself in a std::vector, but storing a plain pointer is fine, even if the thing it points to is an auto_ptr.

I don't see why you'd want to do that, though. The whole point of auto_ptr is to ensure that heap-allocated objects are deleted automatically when they go out of scope. You lose that benefit if the auto_ptr itself has to be deleted manually.

If you want to store heap-allocated objects safely in a vector, you can use std::tr1::shared_ptr instead of auto_ptr, or use Boost's pointer containers. Or, if you're using C++11, std::unique_ptr is like std::auto_ptr except it's safe to use in containers.

于 2012-01-28T01:47:44.123 に答える
0

Yes you could - but it is totally unsafe and will do all sorts of unexpected things that will surprise you.

If you want to store smart pointers in a container have a look at unique_ptr if your compiler supports C++11 stuff

于 2012-01-28T01:46:54.937 に答える