gpt4 book ai didi

c++ - 作为类成员的常量引用

转载 作者:行者123 更新时间:2023-11-30 02:31:59 24 4
gpt4 key购买 nike

假设我有以下类(class):

class BigClass
{
public:
BigClass();
~BigClass();

private:
... // many variables
};

还有一个类:

class SmallClass
{
public:
SmallClass();
~SmallClass();

private:
const BigClass &ref;
};

请注意,我有一个对名为 refBigClass 对象的引用。

  • 这是一个好的设计吗?有更好的方法吗?
  • 当实际的 BigClass 对象超出范围时会发生什么?由于对它的 ref 引用,它会被删除还是会保持事件状态?如果它被删除,那么保持它存活的一个好方法是使用 shared_ptr 而不是引用?

最佳答案

Is that a good design ? Is there a better way to do that ?

如果保证 SmallClass 的生命周期比 BigClass 短,那么它就完全没问题。这种东西在小类中经常看到,用做“仿函数”。

否则使用智能指针:唯一或共享。或弱共享。

What is gonna happen when the actual BigClass object gets out of scope ?

如果 SmallClass 仍然存在并且有引用,它现在是一个无效的引用,你的程序将有未定义的行为。那很糟。它可能不会崩溃,但使用引用会覆盖另一个对象或破坏堆的空闲内存跟踪,或覆盖可能包括函数返回地址的堆栈值。

Will it be deleted or will it stay alive because of the ref reference to it ?

这不是 Java。它将被删除。如果您需要跟踪引用计数,那么您需要一个共享的智能指针。

If it gets deleted, then a good way to do keep it alive would be to have a shared_ptr instead of a reference ?

是的。

关于c++ - 作为类成员的常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com