似乎有std :: auto_ptr和赋值的问题,因此引用的对象似乎由于某种原因而被删除.
std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content
std::auto_ptr<AClass> someVar( new AClass() ); // works fine.
std::auto_ptr<AClass> someVar = std::auto_ptr<AClass>(new AClass()); // works fine.
std::auto_ptr<AClass> someVar;
someVar.reset( new AClass() ); // works fine.
Run Code Online (Sandbox Code Playgroud)
我已经跟踪了它,并且(通过观察调试器中的值)出现问题发生在从用于包装rhs指针而创建的临时std :: auto_ptr_byref()的指针传输中.这是输入auto_ptr(auto_ptr_ref <_Ty> _Right)函数时_Right中包含的值是正确的,但是离开时_Myptr中的值是垃圾.
template<class _Ty>
struct auto_ptr_ref
{ // proxy reference for auto_ptr copying
auto_ptr_ref(void *_Right)
: _Ref(_Right)
{ // construct from generic pointer to auto_ptr ptr
}
void *_Ref; // generic pointer to auto_ptr ptr
};
template<class _Ty>
class auto_ptr
{ // wrap an object pointer to ensure destruction
public:
typedef _Ty element_type;
explicit auto_ptr(_Ty *_Ptr = 0) _THROW0()
: _Myptr(_Ptr)
{ // construct from object pointer
}
auto_ptr(auto_ptr<_Ty>& _Right) _THROW0()
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right auto_ptr
}
auto_ptr(auto_ptr_ref<_Ty> _Right) _THROW0()
{ // construct by assuming pointer from _Right auto_ptr_ref
_Ty **_Pptr = (_Ty **)_Right._Ref;
_Ty *_Ptr = *_Pptr;
*_Pptr = 0; // release old
_Myptr = _Ptr; // reset this
}
auto_ptr<_Ty>& operator=(auto_ptr_ref<_Ty> _Right) _THROW0()
{ // assign compatible _Right._Ref (assume pointer)
_Ty **_Pptr = (_Ty **)_Right._Ref;
_Ty *_Ptr = *_Pptr;
*_Pptr = 0; // release old
reset(_Ptr); // set new
return (*this);
}
Run Code Online (Sandbox Code Playgroud)
起初我以为它搞乱了继承并切断了接口,但即使该类只有一个父类,也会发生这种情况.
如果我们记得,我们可以避免做= new,无论是使用括号还是更改为在rhs上有一个显式的std :: auto_ptr temp,这当然容易出错.
是仅仅这个版本的库被破坏了,还是我刚刚没有得到的一些潜在的东西?
我们还注意到将一个std :: auto_ptr分配给boot :: shared_ptr的类似问题虽然我们现在完全删除了它,但我不记得哪种语法导致了这个问题.
Mic*_*urr 10
第一行:
std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content
Run Code Online (Sandbox Code Playgroud)
应该导致编译器错误.因为没有从原始AClass指针隐式转换为auto_ptr(auto_ptr标记了原始指针的构造函数explicit),所以不允许使用"复制初始化程序"形式进行初始化.
VC9给出以下错误:
C:\temp\test.cpp(23) : error C2440: 'initializing' : cannot convert from 'AClass *' to 'std::auto_ptr<_Ty>'
Run Code Online (Sandbox Code Playgroud)
我尝试过的其他编译器(GCC 3.4.5,Comeau C/C++ 4.3.10.1,Digital Mars)给出了类似的错误.
编辑:
看起来这实际上是VS2005的实现中的一个错误auto_ptr<>(不确定它是在SP1中引入还是从VS2005开始)在VS2008中得到修复.这是问题的MS Connect错误记录:
| 归档时间: |
|
| 查看次数: |
1792 次 |
| 最近记录: |