英文:
C++: Class pointed to by unique_ptr holding a reference to owner, is this bad?
问题
这种模式是否有问题,或者是否可能导致实际上有害的循环?
#include <iostream>
#include <memory>
class Foo;
class Bar {
Foo& m_foo;
public:
Bar (Foo& _foo): m_foo(_foo) {};
};
class Foo {
std::unique_ptr<Bar> m_bar;
bool finished;
void doStuffWithBar();
public:
Foo(): m_bar(std::make_unique<Bar>(*this)), finished(false) {}
bool const& isFinished() { return finished; }
void finish() { finished = true; }
};
int main() {
Foo foo;
while (!foo.isFinished()) {
do {
std::cout << '\n' << "Press a key to exit...";
} while (std::cin.get() != '\n');
foo.finish();
}
std::cout << '\n' << "Exiting now..." << std::endl;
return 0;
}
在正常运行时,Foo
仅在退出应用程序时被销毁。
英文:
Is this a bad pattern, or could this result in a cycle that's actually harmful?
#include <iostream>
#include <memory>
class Foo;
class Bar {
Foo& m_foo;
public:
Bar (Foo& _foo): m_foo(_foo) {};
};
class Foo {
std::unique_ptr<Bar> m_bar;
bool finished;
void doStuffWithBar();
public:
Foo(): m_bar(std::make_unique<Bar>(*this)), finished(false) {}
bool const& isFinished() { return finished; }
void finish() { finished = true; }
};
int main() {
Foo foo;
while (!foo.isFinished()) {
do {
std::cout << '\n' << "Press a key to exit...";
} while (std::cin.get() != '\n');
foo.finish();
}
std::cout << '\n' << "Exiting now..." << std::endl;
return 0;
}
For context, during normal functioning, Foo
would only be destroyed when quitting the app.
答案1
得分: 2
-
Bar
构造函数是public
的,所以没有什么阻止将它与一些无关的Foo
一起使用。你为什么要在只有 Parent 引用的情况下在 Parent 内创建 Child 的想法。如果Bar
的构造函数是private
的,Foo
应该是Bar
的friend
。 -
由于
std::unique_ptr<Bar> m_bar
是Foo
的私有成员,你将如何访问它?在 Child 中对 Parent 的引用有什么用,只有从 Parent 才能访问它?如果m_bar
是public
的,某人可能会意外地破坏这个 happy family。 -
对
Bar
的任何更改都会导致对Foo
的更改,反之亦然。
在你的特定情况下,你想要实现什么?
英文:
Bar
constructor ispublic
so nothing prevents to use it with some irrelevantFoo
. Where your idea to create Child within Parent on Parent reference only. If constructor ofBar
isprivate
Foo
should befriend
ofBar
.- Since
std::unique_ptr<Bar> m_bar
is private toFoo
how will you access it? What is the use for reference to Parent in Child that accessible from Parent only? Ifm_bar
ispublic
someone accidently can break this happy family. - Any change in
Bar
force change inFoo
and vice versa.
What to you want to achieve in your specific case?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论