开发者

Pass pointer to auto_ptr with C++

开发者 https://www.devze.com 2023-02-09 23:58 出处:网络
i have a function that does this: static MyClass* MyFunction(myparams) { return new MyClass(myparams) } and i would be able to call this function inside another one that has the following signature

i have a function that does this:

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

and i would be able to call this function inside another one that has the following signature:

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

but when I try to do it i have a compiler error:

Impossible to convert the first param from MyClass * to std::auto_ptr<_Ty>

why? Thank you for any help

EDIT 1 As asked the myparams types are normal but there is also a T param because the function is ins开发者_Go百科ide a template class


std::auto_ptr<> has an explicit constructor, like any other smart pointer. That means that there is no implicit conversion from T* to std::auto_ptr<T> to prevent from accidentally deleting an object. Hence you need to convert your raw pointed to std::auto_ptr<> explicitly:

MyFunction2(std::auto_ptr<MyClass>(MyFunction()));

It is also a good idea to make your factory functions return a smart pointer instead of a raw pointer, it makes it clear to the reader that the ownership of an object is being transferred to the caller:

static std::auto_ptr<MyClass> MyFunction(myparams)
{
    return std::auto_ptr<MyClass>(new MyClass(myparams));
}


There's no implicit conversion from a raw pointer to an auto_ptr. Just explicitly call it out:

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

Note that the allocated memoty will be destroyed after the call to MyFunction2 because the temporary auto_ptr will be gone, deallocating it.


You might want to call the MyFunction2 function like this...

void f() {
    MyClass* directptr = MyFunction(myparams);
    std::auto_ptr<MyClass> p(directptr);
    MyFunction2(p);
    cout << p.get() << endl; // Prints NULL!
}

However, when MyFunction2 ends the MyClass instance will be deleted, and upon returing p will be NULL and directptr will point to a deleted object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号