Pass pointer to auto_ptr with C++

2k views Asked by At

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

3

There are 3 answers

0
Maxim Egorushkin On BEST ANSWER

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));
}
0
Mark B On

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.

0
vz0 On

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.