C++:unique_ptr指向的类持有对所有者的引用,这是不好的吗?

huangapple go评论56阅读模式
英文:

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

  1. Bar 构造函数是 public 的,所以没有什么阻止将它与一些无关的 Foo 一起使用。你为什么要在只有 Parent 引用的情况下在 Parent 内创建 Child 的想法。如果 Bar 的构造函数是 private 的,Foo 应该是 Barfriend

  2. 由于 std::unique_ptr<Bar> m_barFoo 的私有成员,你将如何访问它?在 Child 中对 Parent 的引用有什么用,只有从 Parent 才能访问它?如果 m_barpublic 的,某人可能会意外地破坏这个 happy family。

  3. Bar 的任何更改都会导致对 Foo 的更改,反之亦然。

在你的特定情况下,你想要实现什么?

英文:
  1. Bar constructor is public so nothing prevents to use it with some irrelevant Foo. Where your idea to create Child within Parent on Parent reference only. If constructor of Bar is private Foo should be friend of Bar.
  2. Since std::unique_ptr<Bar> m_bar is private to Foo how will you access it? What is the use for reference to Parent in Child that accessible from Parent only? If m_bar is public someone accidently can break this happy family.
  3. Any change in Bar force change in Foo and vice versa.

What to you want to achieve in your specific case?

huangapple
  • 本文由 发表于 2023年2月24日 04:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定