passing auto_ptr as shared_ptr

J

Jarek Blakarz

Hi

I would like to pass std::auto_ptr as boost::shared_ptr.
When I do that I receive the following compile error:
conversion from ‘std::auto_ptr<Human>’ to non-scalar type ‘boost::shared_ptr<Human>’ requested

How can I do that correctly ?

#include <memory>
#include <boost/shared_ptr.hpp>

using namespace std;
using namespace boost;

class Human {};

void fun (shared_ptr<Human> s) {}

int main(void)
{
auto_ptr<Human> hAP (new Human);
fun (hAP);

return 0;
}

thanks for help
 
V

Victor Bazarov

I would like to pass std::auto_ptr as boost::shared_ptr.

You can't. Those are unrelated types.
When I do that I receive the following compile error:
conversion from ‘std::auto_ptr<Human>’ to non-scalar type ‘boost::shared_ptr<Human>’ requested

How can I do that correctly ?

What's your definition of "correctly"?
#include <memory>
#include <boost/shared_ptr.hpp>

using namespace std;
using namespace boost;

class Human {};

void fun (shared_ptr<Human> s) {}

int main(void)
{
auto_ptr<Human> hAP (new Human);
fun (hAP);

return 0;
}

'std::auto_ptr' template has a 'get' function that returns the actual
pointer to the object. That member doesn't release the ownership, (like
the 'release' member would). I don't know how 'shared_ptr' is
constructed, but it probably take a naked pointer as its argument. So, try

fun(hAP.get());

V
 
J

Jarek Blakarz

You can't. The lifetime of the object is managed either by the auto_ptr or

shared_ptr mechanism. You have to choose which one you want to use, nothing

good would happen if both mechanisms attempted to manage the object at the

same time.



However, you can easily transfer the ownership from an auto_ptr to a

shared_ptr, if that's what you want to do:



auto_ptr<Human> hAP (new Human);



shared_ptr<Human> s(hAP.release());



Note that hAP is now NULL and is not useful for anything any more.



hth

Paavo

The transfer of ownership from auto_ptr to shared_ptr makes sense. The
following 2 member functions have been defined inside a shared_ptr to
accomplish that:
explicit shared_ptr(std::auto_ptr<Y> & r): px(r.get()), pn()
shared_ptr & operator=( std::auto_ptr<Y> & r )

I have a feeling that the fun(hAP) also makes sense and that's why I feel some
kind of inconsistency why the conversion operator has not been defined.

Please correct me if I'm wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top