0

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

Stefano
  • 3,213
  • 9
  • 60
  • 101
  • 2
    What is the type of myparams in MyFunction, it is missing in the question. – Eric Fortin Feb 10 '11 at 18:16
  • Do you understand the purpose of `auto_ptr`? – Cascabel Feb 10 '11 at 18:18
  • @Eric I've added the myparams types. @Jefromi Yes i understand that auto_ptr let me don't think about pointer destruction and memory deallocation – Stefano Feb 10 '11 at 18:20
  • But it spares you from that by automatically destroying the object once it goes out of scope - which means that if there were an implicit conversion, you could run into some nasty surprises. It's important to understand *what it does*. – Cascabel Feb 10 '11 at 18:23

3 Answers3

9

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));
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

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.

vz0
  • 32,345
  • 7
  • 44
  • 77