[英]Pass pointer to auto_ptr with C++
我有一个功能可以做到这一点:
static MyClass* MyFunction(myparams)
{
return new MyClass(myparams)
}
我将能够在另一个具有以下签名的函数中调用此函数:
void MyFunction2(std::auto_ptr<MyClass> myparam)
但是当我尝试执行此操作时,出现编译器错误:
无法将MyClass *的第一个参数转换为std :: auto_ptr <_Ty>
为什么? 感谢您的任何帮助
编辑1根据要求,myparams类型是正常的,但也有一个T参数,因为该函数在模板类内部
与其他任何智能指针一样, std::auto_ptr<>
具有显式构造函数。 这意味着没有从T*
到std::auto_ptr<T>
隐式转换,以防止意外删除对象。 因此,您需要将原始指针明确转换为std::auto_ptr<>
:
MyFunction2(std::auto_ptr<MyClass>(MyFunction()));
让工厂函数返回一个智能指针而不是原始指针也是一个好主意,它使读者清楚地知道对象的所有权正在转移给调用者:
static std::auto_ptr<MyClass> MyFunction(myparams)
{
return std::auto_ptr<MyClass>(new MyClass(myparams));
}
从原始指针到auto_ptr
没有隐式转换。 只需明确指出:
MyFunction2(std::auto_ptr(MyFunction(params)));
请注意,在调用MyFunction2
之后,分配的备忘录将被销毁,因为临时auto_ptr
将消失并取消分配。
您可能想要像这样调用MyFunction2函数...
void f() {
MyClass* directptr = MyFunction(myparams);
std::auto_ptr<MyClass> p(directptr);
MyFunction2(p);
cout << p.get() << endl; // Prints NULL!
}
但是,当MyFunction2
结束时, MyClass
实例将被删除,并且在重现p
将为NULL, directptr
将指向已删除的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.