考虑一下这个例子:
#include <cstdio>
#include <memory>
struct base
{
base( int i ): i(i) { printf("base ctor\n"); }
~base() { printf("base non-virtual dtor\n"); } // non-virtual
int i;
};
struct derived : public base
{
char* s;
derived(int i): base(i), s(new char[i] )
{
printf("derived ctor\n");
}
~derived()
{
printf("derived dtor\n");
delete [] s;
}
};
int main()
{
printf("Success\n");
//raw pointer
printf("RAW-POINTER\n");
{
base* b = new derived(2);
// ......
delete b; //here memory leak, but it's old- and error-prone code.
}
printf("---END-RAW-POINTER--\n");
//unique-ptr
printf("UNIQUE_PTR\n");
{
// I would that, this doesn't compile, because base- has not virtual destructor.
std::unique_ptr<base> bu( new derived(3) ); // here still memory leak !!!!
}
printf("--END-UNIQUE_PTR--\n");
return 0;
}代码std::unique_ptr<base> bu( new derived(3) );容易禁止与destructor类型的特点。Live code
那么,为什么上面的代码要编译呢?这是标准允许的吗?
编辑:有趣,但使用std::shared_ptr工作,即基和派生dtor都将调用:
printf("SHARED_PTR\n");
{
std::shared_ptr<base> b(new derived(3));
}
printf("--END-SHARED_PTR--\n");
Output:
SHARED_PTR
base ctor
derived ctor
derived dtor
base non-virtual dtor
--END-SHARED_PTR--为什么std::shared_ptr可以调用dervied类dtor,但是std::unique_ptr不能?
EDIT2:很简单,我需要这样的东西:
template< typename T, typename D = default_deleter<T> >
class unique_ptr{
.............
template< typename U >
unique_ptr( U* u ) if ( U != T && T - is class && T is base of U, and D - is default_deleter, and T - has not virtual destructor ) then = delete this ctor.
};发布于 2014-03-02 07:25:09
并不是所有的unique_pointers都是从形式上使用的:
std::unique_ptr<int> p(new int(42));这将不会按照您建议的限制进行编译。班级也是如此:
std::unique_ptr<YourClassHere> p(new YourClassHere);https://stackoverflow.com/questions/22124981
复制相似问题