0

コード スニペット (通常のポインター)

int *pi = new int;
int i = 90;
pi = &i;
int k = *pi + 10;
cout<<k<<endl; 
delete pi;

[Output: 100]

コード スニペット (自動ポインター)

ケース 1:

std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
int k = *pi + 10; //Throws unhandled exception error at this point while debugging.
cout<<k<<endl;
//delete pi; (It deletes by itself when goes out of scope. So explicit 'delete' call not required)

ケース 2:

std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;

[Output: 100]

ケース1でうまくいかなかった理由を誰か教えてください。

4

2 に答える 2

2

ケース1は、単純なポインタをに割り当てることができないため、コンパイルに失敗しますauto_ptr。が処理しているポインタを変更する場合auto_ptrは、resetメソッドを使用できます。

pi.reset(&i);

piこれで、以前に保存していたポインタが削除されます。

ただし、ここでは、削除してはならないスタック割り当て変数のアドレスを格納します。の目的はstd::auto_ptr、動的に割り当てられた変数を管理することです。


VC ++ 2005で観察しているのは、標準では明らかに指定されていない機能(ポインタを割り当てる機能)の実装のバグのようです(std::auto_ptrコンパイルする必要があるかどうかは関係ありません)。

次の標準std::auto_ptrではとにかく非推奨になるので、賢いスマートポインタ(boost::scoped_ptrboost::shared_ptr)を試してみてください。

于 2010-04-23T11:07:12.180 に答える
2

auto_ptスタックに割り当てられた変数に rをバインドしようとしました。

std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;

auto_ptrで割り当てられた変数にのみバインドしてくださいnew。それ以外の場合、auto_ptr はdelete割り当てられた変数をスタックしようとしますが、これは未定義の動作です。

于 2010-04-23T06:29:44.850 に答える