Question about shared_ptr and using it for backreferencing structures

Find and share HowTos to various installations / configurations!
2 posts • Page 1 of 1
flindecke
Posts:69
Joined: Wed Jun 24, 2015 1:54 pm

Question about shared_ptr and using it for backreferencing structures

Post by flindecke »

I am just playing a little bit with shared_ptr introduced in WinCC OA 3.15 Patch 3 :woohoo: .

Now i have a problem using it in a structure like a tree. A node should have a link to it's parent and an array to it's childs.
My Node class looks similar to the following

Code: Select all

class Node {
  shared_ptr _parent;
  dyn_anytype _childs;

  public void appendChild(shared_ptr theChild) {
    dynAppend(_childs, theChild); // works as expected
    theChild._parent = this; // does not work, because this is of type Node and not of type shared_ptr
}
My question is, how to store this as a shared pointer into another instance? Is there a possibility to handle this?

Another thing is, if i have a super class AbstractNode and Node is a subclass of it, i am not able to write the following

Code: Select all

shared_pointer foo;
shared_pointer  bar = new Node(...)
foo = bar; // does not work
It seems to be that implementation of shared_ptr is invariant and not covariant (details about this in http://cpptruths.blogspot.de/2015/11/co ... -in-c.html)
It would be very nice it shared_ptr could behave like covariant c++ std::shared_ptr.

mkoller
Posts:741
Joined: Fri Sep 17, 2010 9:03 am

Re: Question about shared_ptr and using it for backreferencing structures

Post by mkoller »

To the first question:
You must also pass the parent as shared_ptr to the appendChild method.
"this" is not necessarily also a shared_ptr, therefore you must be explicit here.

To your second example: I don't see any error here and it works.

Code: Select all

class AbstractNode
{
  int x;
};

class Node : AbstractNode
{
  int y;
};

main()
{
  shared_ptr foo;
  shared_ptr bar = new Node();
  foo = bar; // does not work
}


2 posts • Page 1 of 1