2016-07-27 7 views
2

私はこれを知っている:あなたはB::~B()のラインの定義のうちを持っていない限り、未定義の動作の抵触auto_ptrを前方宣言

#include <memory> 
class A; 
class B 
{ 
    public: 
     B(A* a) : a_(a) {} 
    private: 
     std::auto_ptr<A> a_; 
}; 

ランを。

そして、ある時点で、gccはこれを言うために使用:

blah/auto_ptr.h: In destructor 'std::auto_ptr<_Tp>::~auto_ptr() [with _Tp = B]': test.hh:6: instantiated from here

blah/auto_ptr.h:173: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.

を、我々はそれを検出し、何も悪いが起こる前にコードを修正することができます。ときどきこれが起こりました。これを切り替えるためのコンパイラオプションはありますか(-Wall -Wextra - Wpedanticはそれをカットしていないようです)

A注:C++ 11への移行は、さまざまな理由からオプションではありません。私はそれを読んでも、同じ問題がunique_ptrに存在します。クラスBのために生成されたデストラクタが正しくPメンバーを破壊した結果

struct A; 
    struct B { 
    std::unique_ptr<A> p; 
    }; 
    struct A { 
    ~A() { 
    } 
    }; 
    { 
    B b; 
    b.p = std::unique_ptr<A>(new A()); // here is you bind default_deletor of already completed type 
    } 

:あなたがunique_ptrをオブジェクトを構築するときに削除者をバインドするため

+1

'std :: auto_ptr'のデザインに根本的な欠陥があります。 C++ 11以降に移行することができない場合でも、代替ソリューションを優先して 'auto_ptr'を削除することを検討する必要があります。 C++の標準ライブラリから型が完全に削除されるというのは、あまりにも欠陥があります。 –

答えて

1

は、unique_ptrを持つそのような問題はありません。

UPDATE:

あなたがC++ 11に移行する予定がない場合は、あなたがunique_ptrをスマートポインタのようなもののauto_ptrの問題を解消することができます。

+0

質問に記載されているように、unique_ptrを使用することは*オプションではありません* –

+0

@TomTannerしかし "と私はそれを読む限り、unique_ptrと同じ問題が存在します"は真ではありません – AnatolyS

+0

それはC++ 11はオプションではありません –

0

実は...

のlibstdC++がstd::unique_ptrのインスタンス化コンパイラエラーになります:

In file included from /usr/local/include/c++/6.1.0/memory:81:0, 
       from main.cpp:1: 
/usr/local/include/c++/6.1.0/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = A]': 
/usr/local/include/c++/6.1.0/bits/unique_ptr.h:236:17: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = A; _Dp = std::default_delete<A>]' 
main.cpp:6:21: required from here 
/usr/local/include/c++/6.1.0/bits/unique_ptr.h:74:22: error: invalid application of 'sizeof' to incomplete type 'A' 
    static_assert(sizeof(_Tp)>0, 

、このような検査が必要とされていないようですが、

#include <memory> 
class A; 
class B 
{ 
    public: 
     B(A* a) : a_(a) {} 
    private: 
     std::unique_ptr<A> a_; 
}; 

Live on Coliru

、それは実装するのは簡単なので、C++標準ライブラリの実装はそのようなチェックをする。

+0

はい、私はauto_ptrでそれを知りません。 –

+0

@TomTannerこれは、 "unique_ptrと同じ問題が存在する"という応答です。これにより移行できない場合は、問題ではないことがわかります。 – milleniumbug

+0

これは、私の移住を妨げているものではありません。私の質問は、auto_ptrが警告なしにコンパイルされている –