I'm currently updating my code by replacing all raw pointer class members with smart pointers. The scenario I'm currently working on is the following:
Having two classes Foo and Bar which know about each other (using raw pointers):
class Bar;
class Foo {
public:b
Foo(){
m_bar = new Bar(this);
}
private:
Bar* m_bar;
};
class Bar {
public:
Bar(Foo* foo) {
m_foo = foo;
}
private:
Foo* m_foo;
};
Since Foo is the creator of "m_bar" and should hold a unique instance of it which is never shared, I thought about making member "m_bar" a unique pointer, resulting in a class Foo that looks like this:
class Foo {
public:
Foo() {
m_bar = std::unique_ptr<Bar>(new Bar(this));
}
private:
std::unique_ptr<Bar> m_bar;
};
But now I'm struggling with class Bar. My idea was to make member "m_foo" a shared pointer, resulting in:
class Bar;
class Foo : public std::enable_shared_from_this<Foo> {
public:
Foo() {
m_bar = std::unique_ptr<Bar>(new Bar(shared_from_this()));
}
private:
std::unique_ptr<Bar> m_bar;
};
class Bar {
public:
Bar(std::shared_ptr<Foo> foo) {
m_foo = foo;
}
private:
std::shared_ptr<Foo> m_foo;
};
But this will throw a "bad weak pointer" exception because (as far as I found out) you can only share the "this"-pointer (shared_from_this()) after the object has been created.
Problem: I want "this" to be shared during object creation because it's necessary for the program to run correctly and it could be forgotten if you do it via function call after the object creation.
Thanks for any help.
Aucun commentaire:
Enregistrer un commentaire