auto_ptr的一个疑问
我在最近编程时遇到了如下的一个疑问:倒底是微软错了还是我错了?详细说明如下:
C++STL书中关于auto_ptr的析构函数定义是 "delete ap "
而VS.net 2005中auto_ptr的析构函数定义是 "delete (_Ty *)_Myptr; "
由于多了一个(_Ty *),析构函数的调用可能会出现错误。例如下面的例子:
#include <memory>
using namespace std;
class Base{
public:
virtual ~Base(){}
};
class Derive : public Base{
public:
virtual ~Derive() {}
};
class Interface{
public:
Interface()
{
p = new Derive();
}
~Interface()
{
//p.release();
}
protected:
auto_ptr <Base> p;
};
void main()
{
Interface int1;
}
由于Interface中的P是Base实例的auto_ptr,而在与指针关联时关联的是Derive的实例。这样如果在.net 2005下编译时,函数的析构将导致直接对基类的析构函数的调用:因而出现错误。
我用auto_ptr时间不长,不知道是不是因为auto_ptr本身就不能按照上述程序的方式用,还是微软错了。
[解决办法]
在你的2个析构函数里加打印,把打印结果贴出来。
[解决办法]
出现什么错误啊? Crash啊?
那也不是STL的错误了。
[解决办法]
改
#include <memory>
using namespace std;
class Base{
public:
virtual ~Base(){}
};
class Derive : public Base{
public:
virtual ~Derive() {}
};
class Interface{
public:
Interface() : p(new Derive())
{
}
~Interface()
{
//p.release();
}
protected:
auto_ptr <Base> p;
};
int main()
{
Interface int1;
return 0;
}
[解决办法]
Chiyer(星羽) 的修改是对的.
楼主的担心可能是怕auto_ptr析构中的转换不能调用Derive 的析构函数. 因为Derive 析构函数是virtual 的,所以不会发生这种情况.
[解决办法]
C++ Primer 3/e中文版 8.3.2 P343
我们不能够在 auto_ptr 对象被定义之后,再用 new 表达式创建对象的地址来直接向其赋值。
也就是说。。
p = new Derive();
这个是 not allowed by design.
正确改法:推荐用 Chiyer 的。另一种可以通过的改法
p.reset (new Derive());