是否可以创建一个没有模板的简单智能指针基类?
我想知道是否可以在不使用模板的情况下创建智能指针基类?
我见过很多实现,但都使用模板。 例如,在派生其他类的基类中实现智能指针逻辑。
I was wondering if it is possible to create a smart pointer baseclass without using a template?
I have seen a number of implementations but all use tempalates.
For example, implementing the smart pointer logics in a base class which other classes derive from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是你的指针成员的类。
在像 C# 这样的语言中这是可能的,因为有一个“object”类,所有其他类都派生自该类。在这种情况下,您将失去类型安全性。
然而,在 C++ 中你没有这样的东西,这给你留下了 2 个选择:
因此,最好的方法是使用模板。
顺便说一句,模板的想法非常好,以至于C#在某个版本之后开始使用它。
The problem is the class of your pointer member.
In languages like C# it is possible, because there is an "object" class, from which every other class derives. You would lose type safety in that case.
However, in C++ you don't have such a thing, which leaves you with 2 choices:
Thus, the best way is to use templates.
By the way, the idea of template is so good that C# started to use it after some version.
如果您希望智能指针类充当仅特定数据类型的资源的资源管理类,那么您不需要模板。
如果您计划编写通用资源管理器类,那么您确实需要一个模板类。
If you want your smart pointer class to act as a resource managing class for only a particular data type of resource then you dont need a template.
If you are planning to write a generic resource manager class then you do need a template class.
使用这种方法的问题是无法添加方法。是的,如果您愿意,您可以使用继承来创建智能指针,但结果会相当有限。在这种情况下,继承不是最好的解决方案。动态多态性很少是最好的解决方案,但这是一个不同的、更大的讨论(请注意,我没有说过它永远)。
The problem with using this approach is that you can't add methods. Yes, you can use inheritance for creating smart pointers if you want but the result would be rather limited. In this case, inheritance is not the best solution. Dynamic polymorphism is rarely the best solution but this is a different and much bigger discussion (note that I haven't said it never is).
我不知道为什么
I'm not sure why