0

我有一个功能可以做到这一点:

static MyClass* MyFunction(myparams)
{
    return new MyClass(myparams)
}

我将能够在另一个具有以下签名的函数中调用此函数:

void MyFunction2(std::auto_ptr<MyClass> myparam)

但是当我尝试这样做时,我遇到了编译器错误:

无法将第一个参数从 MyClass * 转换为 std::auto_ptr<_Ty>

为什么?感谢您的任何帮助

编辑 1 询问 myparams 类型是正常的,但也有一个 T 参数,因为该函数在模板类中

4

3 回答 3

9

std::auto_ptr<>与任何其他智能指针一样,具有显式构造函数。这意味着没有隐式转换 from T*tostd::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));
}
于 2011-02-10T18:18:55.297 回答
0

没有从原始指针到auto_ptr. 只需明确地调用它:

MyFunction2(std::auto_ptr(MyFunction(params)));

请注意,分配的内存将在调用后被销毁,MyFunction2因为临时auto_ptr将消失,释放它。

于 2011-02-10T18:18:29.060 回答
0

您可能想像这样调用 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指向已删除的对象。

于 2011-02-10T18:21:12.647 回答