2016-07-27 53 views
2

我知道這一點:相抵觸的未定義行爲auto_ptr的轉發聲明

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

運行,除非你有一個徹頭徹尾的B::~B()線定義的;

在一個點,用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似乎不會將其切換)

注意:由於各種原因,遷移到C++ 11和unique_ptr不是一個選項,正如我讀到的,unique_ptr存在同樣的問題。

+1

'std :: auto_ptr'的設計基本上是有缺陷的。即使你不能移動到C++ 11或更新的版本,你應該考慮拋棄'auto_ptr'來支持替代解決方案。它很有缺陷,這種類型將從C++ 17中的標準庫中完全刪除。 –

回答

1

有沒有這樣的問題的unique_ptr,因爲當您構造的unique_ptr對象綁定deletor:

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 
    } 

其結果爲類B的析構函數生成正確地破壞該p構件。

UPDATE:

如果你不打算遷移到C++ 11,你能不能像的unique_ptr智能指針,以消除auto_ptr的問題。

+0

正如問題所述,使用unique_ptr *不是*選項 –

+0

@TomTanner但「據我所知,與unique_ptr存在相同的問題」不是真的 – AnatolyS

+0

這不是移動到C++的原因11不是一個選項 –

0

其實...

的libstdC++使得std::unique_ptr實例化一個編譯器錯誤:

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

Live on Coliru

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, 

雖然這樣的檢查似乎並不需要,它的實現是微不足道的,所以C++標準庫的實現應該是可以實現的有這樣的檢查。

+0

是的,但我沒有得到與auto_ptr。 –

+0

@TomTanner這是對「unique_ptr存在同樣問題」的迴應。如果這阻止了您的遷移,那麼您會發現這不是問題。 – milleniumbug

+0

這不是什麼阻止我遷移。無論如何,我的問題更多地是關於auto_ptr編譯時沒有警告的事實 –