Assignment Operator with auto_ptr

C

Chummaid

Hello All,
Can somebody please explain why the following is not supported ?

class A{};

A* a = new A();

auto_ptr <A> aptr = *a;

// though this is supported.

auto_ptr <A> aptr(a);

Thanks in advance
CID
 
K

Kristo

Hello All,
Can somebody please explain why the following is not supported ?

class A{};

A* a = new A();

auto_ptr <A> aptr = *a;

Contrary to what the thread subject says, this invokes auto_ptr's
constructor. You're trying to pass the A object itself, not a pointer
to it. This is the correct way to do it:
// though this is supported.

auto_ptr <A> aptr(a);

If you want to use the equals sign syntax, this line would be:
auto_ptr<A> aptr = a;

Kristo
 
C

CID

Kristo said:
Contrary to what the thread subject says, this invokes auto_ptr's
constructor. You're trying to pass the A object itself, not a pointer
to it. This is the correct way to do it:


If you want to use the equals sign syntax, this line would be:
auto_ptr<A> aptr = a;

Kristo

This will result in the following error in g++, which was my first
doubt was.

error: conversion from `A*' to non-scalar type
`std::auto_ptr<A>' requested

Thanks for the reply
CID
 
S

Stefan Strasser

CID said:
This will result in the following error in g++, which was my first
doubt was.

error: conversion from `A*' to non-scalar type
`std::auto_ptr<A>' requested


that's because the constructor of auto_ptr is "explicit", and there's a
obvious reason for it.
use
auto_ptr<A> aptr=auto_ptr<A>(a);
instead
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top