2

配列へのスマートポインターを作成したい場合、最善の方法は使用することであることを十分に認識しています

     boost::shared_array<T>( new T[20] );

私が理解していないのは、この型の共有ポインタが範囲外になったときに発生するクラッシュです。

     boost::shared_ptr<T>( new T[20] );

上記のコードは、他の要素をそのままにして配列の最初の要素で削除を呼び出すため、リークが発生すると常に考えていましたが、そうではなく、セグメンテーション違反があります。

理由を理解するのを手伝ってもらえますか? 共有ポインターを使用せずにプレーンなバニラポインターを使用すると、最悪の動作になります

       CMyClass *p = new CMyCLass[10];
       ///....do stuff
       delete p;

       *** glibc detected *** ./test: munmap_chunk(): invalid pointer: 0x088eb00c ***
4

4 に答える 4

4

Can you help me understanding why? I have worst behavior if I don't use the shared pointer but a plain vanilla pointer

Because your code has an Undefined Behavior.

CMyClass *p = new CMyCLass[10];
///....do stuff
delete []p;
      ^^^^ <-------------that is Missing!

You need to use delete [].

  1. If you allocated using new you must use delete.
  2. If you allocated using new [] you must use delete []

Doing otherwise leads to Undefined Behavior. And one its Undefined Behavior then your program might show any behavior.It might crash or work or whatever(literally) so all safe bets are off.

How to use custom deallocation with shared_ptr?

For shared_ptr you should use your own custom deletor function to deallocate appropriately. In case of array allocation using new [], you need to use delete []. Something like:

template
class CustomDeleter
{
public:
    void operator () (T* d) const
    {
        delete [] d;
    }
};

int main ()
{
    std::shared_ptr array(new Myclass[256], CustomDeleter());
    return 0;
}
于 2012-05-27T15:24:02.827 に答える
2

要素が ed である場合は、dnewである必要があります。deleteed の場合は、 dnew[]にする必要があります。delete[]

shared_ptrが要素deleteの代わりにしようとすると、問題が発生すると思われます。delete[]

于 2012-05-27T15:24:13.407 に答える
1

を使用して配列を割り当てる場合は、それを解放するnew T[N]()ために呼び出す必要がありますが、呼び出しによりエラーが発生します。最も簡単な方法は、参照カウント ポインターに配列を格納するために使用することです。delete []shared_ptrdeleteboost::shared_array<T>

于 2012-05-27T15:26:36.603 に答える
0

スマート ポインターの配列を使用しないのはなぜですか?

于 2012-05-27T16:26:06.597 に答える