Back-Pointer

Hey,
i'm lacking a proper search term for my problem, so i hope this question hasn't been answered already.
So, i have a class called Parent.On instantiation it creates two other objects and holds reference to them with shared_pointers.The other objects need to know, who their "creator" is.Because of that they store a simple pointer to the parent object.Is the following approach correct for this use ? Or are there any reasons to use weak_ptr or anything different from below ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Member {
	Parent* p = nullptr;
	Member(Parent* p) : p(p) {}
	Parent* getParen() { return p; }
};

class Parent {
	shared_ptr<Member> m1{ nullptr };
	shared_ptr<Member> m2{ nullptr };
	int status = 0;

	Parent() {
		m1 = make_shared<Member>(this);
		m2 = make_shared<Member>(this);
	}
};
Last edited on
That looks pretty good to me.

You might want to initialize m1 and m2 as part of the Constructor's initialization list rather than in the body so you don't initialize and then copy.

In the Member class, should p be a shared_ptr?
I would think unique_ptr would be more appropriate here. Is ownership actually being shared?
If a class invariant for Member is: there must be a parent,

1
2
3
4
5
6
7
8
9
10
11
class Parent ;

class Member {
    
    Parent& p ; // reference

    public:
        explicit Member( Parent& p ) : p(p) {}
        Parent& getParent() { return p; }
        // ...
};


If the constructor of Parent has to create the member objects directly (creation is non-polymorphic, member objects are not shared),

1
2
3
4
5
6
7
class Parent {

    Member m1 {*this} ;
    Member m2 {*this} ;
    
    // ...
};
@doug4 yes that makes sense, thanks!
If p would be a shared_ptr to parent and both member objects would be destroyed, the destructor of the parent object would be called, right?

@cire it aactually is shared, i just stripped down the example


That's a great idea, if shared pointers aren't needed! I'm always too focused on the constructor :D
1
2
3
4
5
6
7
class Parent {

    Member m1 {*this} ;
    Member m2 {*this} ;
    
    // ...
};


By the way:
There is no way to create a shared pointer of an object while in the constructor of the same object, right?
That totally makes sense to me, just want to be sure...
1
2
3
4
class Parent {
    Member m1 {std::shared_ptr<Parent>(*this)};
//....
};

Topic archived. No new replies allowed.