Wrapping pointer this into a shared_ptr [duplicate] - c++

I am currently trying to learn how to use smart pointers. However while doing some experiments I discovered the following situation for which I could not find a satifying solution:
Imagine you have an object of class A being parent of an object of class B (the child), but both should know each other:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
The question is how can an object of class A pass a std::shared_ptr of itself (this) to its child?
There are solutions for Boost shared pointers (Getting a boost::shared_ptr for this), but how to handle this using the std:: smart pointers?

There is std::enable_shared_from_this just for this purpose. You inherit from it and you can call .shared_from_this() from inside the class. Also, you are creating circular dependencies here that can lead to resource leaks. That can be resolved with the use of std::weak_ptr. So your code might look like this (assuming children rely on existence of parent and not the other way around):
class A;
class B;
class A
: public std::enable_shared_from_this<A>
{
public:
void addChild(std::shared_ptr<B> child)
{
children.push_back(child);
// like this
child->setParent(shared_from_this()); // ok
// ^^^^^^^^^^^^^^^^^^
}
private:
// note weak_ptr
std::list<std::weak_ptr<B>> children;
// ^^^^^^^^
};
class B
{
public:
void setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
}
private:
std::shared_ptr<A> parent;
};
Note however, that calling .shared_from_this() requires that this is owned by std::shared_ptr at the point of call. This means that you cannot create such object on stack anymore, and generally cannot call .shared_from_this() from within a constructor or destructor.

You have several problems in you design, that seem to stem from you misunderstanding of smart pointers.
Smart pointers are used to declare ownership. You are breaking this by declaring that both the parents owns all children, but also that each child own it's parent. Both can't be true.
Also, you are returning a weak pointer in getChild(). By doing so, you are declaring that the caller shouldn't care about the ownership. Now this can be very limiting, but also by doing so, you must make sure that the child in question won't get destroyed while any weak pointers are still held, if you would use a smart pointer, it would get sorted out by itself.
And the final thing. Usually, when you are accepting new entities, you should usually accept raw pointers. Smart pointer can have their own meaning for swapping children between parents, but for general usage, you should accept raw pointers.

Related

Not able to pass around the same reference of a shared pointer [duplicate]

I am currently trying to learn how to use smart pointers. However while doing some experiments I discovered the following situation for which I could not find a satifying solution:
Imagine you have an object of class A being parent of an object of class B (the child), but both should know each other:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
The question is how can an object of class A pass a std::shared_ptr of itself (this) to its child?
There are solutions for Boost shared pointers (Getting a boost::shared_ptr for this), but how to handle this using the std:: smart pointers?
There is std::enable_shared_from_this just for this purpose. You inherit from it and you can call .shared_from_this() from inside the class. Also, you are creating circular dependencies here that can lead to resource leaks. That can be resolved with the use of std::weak_ptr. So your code might look like this (assuming children rely on existence of parent and not the other way around):
class A;
class B;
class A
: public std::enable_shared_from_this<A>
{
public:
void addChild(std::shared_ptr<B> child)
{
children.push_back(child);
// like this
child->setParent(shared_from_this()); // ok
// ^^^^^^^^^^^^^^^^^^
}
private:
// note weak_ptr
std::list<std::weak_ptr<B>> children;
// ^^^^^^^^
};
class B
{
public:
void setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
}
private:
std::shared_ptr<A> parent;
};
Note however, that calling .shared_from_this() requires that this is owned by std::shared_ptr at the point of call. This means that you cannot create such object on stack anymore, and generally cannot call .shared_from_this() from within a constructor or destructor.
You have several problems in you design, that seem to stem from you misunderstanding of smart pointers.
Smart pointers are used to declare ownership. You are breaking this by declaring that both the parents owns all children, but also that each child own it's parent. Both can't be true.
Also, you are returning a weak pointer in getChild(). By doing so, you are declaring that the caller shouldn't care about the ownership. Now this can be very limiting, but also by doing so, you must make sure that the child in question won't get destroyed while any weak pointers are still held, if you would use a smart pointer, it would get sorted out by itself.
And the final thing. Usually, when you are accepting new entities, you should usually accept raw pointers. Smart pointer can have their own meaning for swapping children between parents, but for general usage, you should accept raw pointers.

Passing `this` to child object

Is this method of passing and storing this to a child object still considered 'acceptable' when using C++17, or is there a more appropriate method, in line with the language and standard?
I am specifically asking regarding passing and storing the Parent object as a plain pointer.
class Child
{
public:
void SetParent(Parent* p)
{
_parent = p;
}
private:
Parent* _parent;
};
class Parent
{
public:
void MyMethod()
{
Child c;
c.SetParent(this);
}
};
Post-C++11 you can use std::weak_ptr<Parent>, assuming you're using std::shared_ptr<Parent> (and inherit from std::enable_shared_from_this in order to generate a std::shared_ptr or std::weak_ptr internally).
Aside from that, yes, it's still acceptable to use a raw pointer to represent lack of ownership or back pointer (until the committee adds some kind of std::owned_ptr<T> / std::ptr_view<T> class).

Composition with a pointer

I am having trouble with RobotControl class members. The UML specifies the relation between RobotControl’s position and RangeSensor as composition. Doesn't using pointers for them, make them aggregation? How should I declare - create these members with respect to UML, or has UML mistaken?
Pointers in C++ can be used for both aggregation and composition. The distinction is, as correctly noted by Douglas, whether the lifetime of the objects is interconnected. In other words: Is the child destroyed when the parent is destroyed? The answer Yes stands for composition, No for aggregation.
How do we distinguish these cases in a C++ code?
Pointers in C++ can mean the ownership of another (dynamically created) object, or just refer to an object owned by someone else. Let’s show the differences in examples. I’ll explain why pointers can be useful for each type of relationship.
Aggregation with a pointer
In this case, it is fine to only forward-declare the class Child before class Parent declaration and the child member can be set and re-set during the lifetime of the Parent.
class Child;
class Parent
{
public:
Parent(Child* ch) : child(ch) {}
Parent() : child(NULL) {}
void setChild(Child* ch) { child = ch; }
private:
Child* child;
};
Composition with a pointer
The longest example shows that we can dynamically create and destroy the child using a pointer. The child’s lifetime is strongly interconnected with the Parent. However, we can still swap children during the lifetime of the Parent thanks to pointers. This solution also allows to only forward-declare class Child in the header file unlike the alternative below.
// --- header file
class Child;
class Parent
{
public:
Parent();
~Parent();
void renewChild();
private:
Child* child;
};
// --- source file
#include "child.h"
Parent::Parent()
: child(new Child)
{
}
Parent::~Parent()
{
delete child;
}
void Parent::renewChild()
{
delete child;
child = new Child;
}
Disclaimer
This example is a subject to the Rule of three/five/zero. I am intentionally letting the implementation of missing recommended methods up to the user, keeping this answer dialect-agnostic and as simple as possible.
Composition without pointers
Instead of writing constructor and destructor manually, you can just declare child in the class declaration and let the compiler to do the construction and destruction for you. This is valid as long as the class Child’s constructor requires no parameters (otherwise you’d need to write class Parent’s constructor manually) and the class Child is fully declared before the declaration of class Parent.
#include "child.h"
class Parent
{
private:
Child child;
};
Aggregation without pointers
To be complete, the alternative to using pointers for aggregation is using a reference. However, this prevents swapping children during the lifetime of the Parent object.
class Child;
class Parent
{
public:
Parent(Child& ch) : child(ch) {}
private:
Child& child;
};

std::shared_ptr of this

I am currently trying to learn how to use smart pointers. However while doing some experiments I discovered the following situation for which I could not find a satifying solution:
Imagine you have an object of class A being parent of an object of class B (the child), but both should know each other:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
The question is how can an object of class A pass a std::shared_ptr of itself (this) to its child?
There are solutions for Boost shared pointers (Getting a boost::shared_ptr for this), but how to handle this using the std:: smart pointers?
There is std::enable_shared_from_this just for this purpose. You inherit from it and you can call .shared_from_this() from inside the class. Also, you are creating circular dependencies here that can lead to resource leaks. That can be resolved with the use of std::weak_ptr. So your code might look like this (assuming children rely on existence of parent and not the other way around):
class A;
class B;
class A
: public std::enable_shared_from_this<A>
{
public:
void addChild(std::shared_ptr<B> child)
{
children.push_back(child);
// like this
child->setParent(shared_from_this()); // ok
// ^^^^^^^^^^^^^^^^^^
}
private:
// note weak_ptr
std::list<std::weak_ptr<B>> children;
// ^^^^^^^^
};
class B
{
public:
void setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
}
private:
std::shared_ptr<A> parent;
};
Note however, that calling .shared_from_this() requires that this is owned by std::shared_ptr at the point of call. This means that you cannot create such object on stack anymore, and generally cannot call .shared_from_this() from within a constructor or destructor.
You have several problems in you design, that seem to stem from you misunderstanding of smart pointers.
Smart pointers are used to declare ownership. You are breaking this by declaring that both the parents owns all children, but also that each child own it's parent. Both can't be true.
Also, you are returning a weak pointer in getChild(). By doing so, you are declaring that the caller shouldn't care about the ownership. Now this can be very limiting, but also by doing so, you must make sure that the child in question won't get destroyed while any weak pointers are still held, if you would use a smart pointer, it would get sorted out by itself.
And the final thing. Usually, when you are accepting new entities, you should usually accept raw pointers. Smart pointer can have their own meaning for swapping children between parents, but for general usage, you should accept raw pointers.

How to use automatic reference counting and virtual functions together in the C++?

I had been searching the answer for this problem for a long.
I want to use shared data (shared_ptr or something similar) where it's possible and where it's necessary of course. But I also want to use virtual functions. As you can see below, there is a contradiction in the usage of them together.
I protect the data of class in this manner:
class MyObject {
public:
void method() {
// no memory leak here, because this contains
// count of references of Data inside shared_ptr
OtherObject::otherMethod(this);
}
private:
class Data {};
shared_ptr<Data> data;
};
Because if I simply nest my class MyObject inside the shared_ptr, I will not be able to pass "this" raw pointer safely outside of the MyObject class in some method. Raw pointer is not protected with reference counting.
Example:
class MyObject {
public:
void method() {
// memory leak here, because this does not contain
// count of references of Data or of self (MyObject)
OtherObject::otherMethod(this);
}
private:
class Data {};
Data data;
};
...
shared_ptr<MyObject> crazyLeakingObject;
crazyLeakingObject leaks, because it has MyObject inside with all its data and methods, but it is only MyObject without any information about count of the references. In the MyObject's methods we have no such information.
The first approach I use when I do not need virtual functions. But the second is for the virtual functions. As you know, you can access vtable only through pointer (raw pointer) of the existing object. But raw pointers and protected shared pointers are opposites.
Usage of this two approaches together makes the architecture of my projects messy.
And there is a leaks in the second approach.
Is there a way to use virtual functions and automatic reference counting? Where I can find an examples? Did you faced with the problem?
I am not a native English speaker, so you may ask for the clarifications.
Thanks in advance.
You can use virtual functions with shared_ptr:
struct Base {
virtual ~Base() {}
void foo() { std::cout << "base\n"; }
};
struct Derived : Base {
void foo() { std::cout << "derived\n"; }
};
int main() {
shared_ptr<Base> ptr(new Derived());
ptr->foo(); // prints "derived"
} // object is deleted at function return
If your OtherObject::otherMethod stores its argument away somewhere, such that it can last longer than the caller's reference, then you might have a problem. You could pass a shared_ptr to otherMethod instead of a raw pointer, and use Boost's enable_shared_from_this so that the code in method can get the shared pointer to the object itself, to pass to otherMethod. But without seeing any of the relevant code, I don't know whether or not it's necessary or a good idea.
You want to use std::enable_shared_from_this to pass the this pointer of a shared object...
http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/enable_shared_from_this