鑑於這種碼之間的循環依賴關係:打破一個shared_ptr和的unique_ptr
#include <iostream>
#include <memory>
class Controller;
class View {
public:
~View() {
std::cout << "Disposing View" << std::endl;
}
void SetObserver(std::shared_ptr<Controller> a_observer) {
observer = a_observer;
}
private:
std::shared_ptr<Controller> observer;
};
class Controller : public std::enable_shared_from_this<Controller> {
public:
static std::shared_ptr<Controller> Create(std::unique_ptr<View> view) {
//Can't use std::make_shared due to visibility rules :(
auto controller = std::shared_ptr<Controller>(new Controller(std::move(view)));
controller->Init();
return controller;
}
~Controller() {
std::cout << "Disposing Controller" << std::endl;
}
private:
std::unique_ptr<View> view;
explicit Controller(std::unique_ptr<View> a_view) : view(std::move(a_view)) {}
Controller(const Controller&) = delete;
void Init() {
view->SetObserver(shared_from_this());
}
};
int main() {
auto view = std::make_unique<View>();
auto controller = Controller::Create(std::move(view));
return 0;
}
我認爲controller
對象將永遠不會被設置(由running it證實)。
爲了減輕這個問題,是否足以使observer
變量變爲weak_ptr
而不是shared_ptr
?
除此之外,鑑於上述設計,是否還有其他潛在問題需要我注意?
*「由於可見性規則,不能使用std :: make_shared」* - 請參閱http://stackoverflow.com/questions/8147027/how-do-i-call-stdmake-shared-on-a-class -with-only-protected-or-private-const –
@ChristianHackl感謝您將這個答案鏈接起來,但我想我現在堅持使用'new'。我不想在代碼中添加太多混亂。 –