auto_ptr: reassigning to member of owned object

  • Thread starter Joost Ronkes Agerbeek
  • Start date
J

Joost Ronkes Agerbeek

Is it legal to reassign an auto_ptr to another auto_ptr that is a member of
the object the auto_ptr is holding before the reassignment? (Confused yet?
:p)

#include <memory>
class Node
{
public:
Node() : next(0) {}
Node(Node* node) : next(node) {}
std::auto_ptr<Node> next;
};

void main()
{
Node node(new Node(new Node()));
node.next = (*node.next).next; // <-- is this valid?
}

As I see it, this program could cause problems if the object node.next owns
is deleted before (*node.next).next is evaluated. I even think the auto_ptr
assignment operator needs to make a temporary copy of (*node.next).next.
The above code compiles and runs on my system, but is it legal according to
the C++ Standard?

tia,
Joost
 
G

Gianni Mariani

Joost said:
Is it legal to reassign an auto_ptr to another auto_ptr that is a member of
the object the auto_ptr is holding before the reassignment? (Confused yet?
:p)

#include <memory>
class Node
{
public:
Node() : next(0) {}
Node(Node* node) : next(node) {}
std::auto_ptr<Node> next;
};

void main()

obligatory - main must return int comment.
{
Node node(new Node(new Node()));
node.next = (*node.next).next; // <-- is this valid?
}

As I see it, this program could cause problems if the object node.next owns
is deleted before (*node.next).next is evaluated.

That's kind of hard since operator= can't be called until
(*node.next).next is evaluated.

I even think the auto_ptr
 
J

Joost Ronkes Agerbeek

void main()
obligatory - main must return int comment.
You're right of course. My mistake.
That's kind of hard since operator= can't be called until
(*node.next).next is evaluated.

That makes sense. :-D

Problem solved then :), thanks a bunch.
 

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,053
Latest member
BrodieSola

Latest Threads

Top