2016-07-27 51 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编译时没有警告的事实 –