I dont exactly know, how to handle the problem, where one class uses shared pointers but I want to call its method from inside other class via this pointer.
class Bar {
public:
Bar() = default;
~Bar() = default;
void OnChange(std::shared_ptr<Foo> foo) { ... }
}
class Foo {
public:
Foo(std::shared_ptr<Bar> bar) : bar(bar) {};
~Foo() = default;
void Run() {
bar->OnChange(this); // <=== this wont work
}
private:
std::shared_ptr<Bar> bar;
}
How can I create "clean" design so that Foo
can cann OnChange
form Bar
?
- Should I use
std::enable_shared_from_this
forFoo
? - Should I add
OnChange(Foo* foo)
toBar
? - Some other solution?
shared_ptr
is probably the wrong tool for your purpose. See: stackoverflow.com/questions/10826541/…OnChange
need to share ownership? Is there a good reason it can't be passed a reference instead?Bar::OnChange(const Foo &foo)
?