简体   繁体   中英

Pass pointer to auto_ptr with C++

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 inside 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM