我有一个功能,这样做:
static MyClass* MyFunction(myparams)
{
return new MyClass(myparams)
}
Run Code Online (Sandbox Code Playgroud)
我可以在另一个具有以下签名的函数内调用此函数:
void MyFunction2(std::auto_ptr<MyClass> myparam)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这样做时,我有一个编译器错误:
无法将第一个参数从MyClass*转换为std :: auto_ptr <_Ty>
为什么?感谢您的任何帮助
编辑1 根据要求,myparams类型是正常的,但也有一个T param,因为该函数在模板类中
std::auto_ptr<>有一个显式的构造函数,就像任何其他智能指针一样.这意味着没有隐式转换T*,std::auto_ptr<T>以防止意外删除对象.因此,您需要将原始指向转换为std::auto_ptr<>显式:
MyFunction2(std::auto_ptr<MyClass>(MyFunction()));
Run Code Online (Sandbox Code Playgroud)
使工厂函数返回智能指针而不是原始指针也是一个好主意,它使读者清楚地知道对象的所有权正在传递给调用者:
static std::auto_ptr<MyClass> MyFunction(myparams)
{
return std::auto_ptr<MyClass>(new MyClass(myparams));
}
Run Code Online (Sandbox Code Playgroud)