gpt4 book ai didi

c++ - 在 C++ OOP 中,谁负责删除传递给构造函数的对象

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:31 26 4
gpt4 key购买 nike

例如,

I have an account generator class need a random method to decide username and password. Random has many ways to implement, so it is an interface with many subclass. Account generator class accept Random object in constructor.

在 Java 中我们不关心对象的删除。但我现在正在用 C++ 来做。我的问题是,如果我在 main() 中执行以下操作

Random random=new StdRandom();
AccGen accGen=new AccGen(random);

我应该删除 main() 中的“随机”,还是应该将它放在 AccGen 的析构函数中?

Edit:

Even after the question is being answered very well, I think I may still state the reason that why do I use pointer, in order to help somebody facing the same problem.

The reason I use pointer, is to apply many patterns like Factory and Behavior. Non-pointer variable seems not able to be an Interface with pure virtual method, which cannot present overrides.

In a design view, I think the creator of an object is always responsible for its deletion. That is why it makes me confused. All the caller wants, it an AccGen object. I passed a random object is to decide the implementation of Random, inside AccGen. Then Random object is not a participant in caller's level, then why should the caller be responsible for its deletion. But the fact is, in some case, the random is useful in the following actions in caller's level. The given example is really just an example.

After a study of smart pointer, Unique pointer really is the solution of my problem. It makes pointer become more specific, in terms of to state the purpose of creating such pointer.

To summarize, if an object is useful after passed to constructor, then the type would be pure pointer and with no deletion in destructor. If the object is useless in caller's level, then the type should be unique pointer.

最佳答案

在 C++ 中我们使用 smart pointers所以我们不关心删除。

关于c++ - 在 C++ OOP 中,谁负责删除传递给构造函数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845463/

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