为什么我不应该总是使用 shared_ptr 和 unique_ptr 而是使用普通指针? [英] Why shouldn't I use shared_ptr and unique_ptr always and instead use normal pointers?

查看:42
本文介绍了为什么我不应该总是使用 shared_ptr 和 unique_ptr 而是使用普通指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 C#obj-c 的背景,所以 RC/GC 是我(仍然)珍视的东西.当我开始更深入地学习 C++ 时,我不禁想知道为什么我会在普通指针如此不受管理而不是其他替代解决方案的情况下使用它们?

I have a background in C# and obj-c so RC/GC are things I (still) hold dear to me. As I started learning C++ in more depth, I can't stop wondering why I would use normal pointers when they are so unmanaged instead of other alternative solutions?

shared_ptr 提供了一种很好的方式来存储引用并且不会在不删除它们的情况下丢失它们的踪迹.我可以看到普通指针的实用方法,但它们似乎只是不好的做法.

the shared_ptr provides a great way to store references and not lose track of them without deleting them. I can see practical approaches for normal pointers but they seem just bad practices.

有人可以举例说明这些替代方案吗?

Can someone make of case of these alternatives?

推荐答案

正如其他人提到的,在 C++ 中,您必须考虑所有权.话虽如此,我目前正在开发的 3D 网络多人 FPS 有一个官方规则,称为不得新建或删除".它只使用共享的和唯一的指针来指定所有权,并在我们需要与 C API 交互的任何地方使用从它们中检索的原始指针(使用 .get()).性能下降并不明显.我以此为例说明性能损失可以忽略不计,因为游戏/模拟通常具有最严格的性能要求.

As someone else mentioned, in C++ you have to consider ownership. That being said, the 3D networked multiplayer FPS I'm currently working on has an official rule called "No new or delete." It uses only shared and unique pointers for designating ownership, and raw pointers retrieved from them (using .get()) everywhere that we need to interact with C API's. The performance hit is not noticeable. I use this as an example to illustrate the negligible performance hit since games/simulations typically have the strictest performance requirements.

这也显着减少了调试和查找内存泄漏所花费的时间.理论上,设计良好的应用程序永远不会遇到这些问题.然而,在现实生活中,使用设计不佳的截止日期、遗留系统或现有游戏引擎,它们在游戏等大型项目中是不可避免的……除非您使用智能指针.如果您必须动态分配,没有足够的时间来设计/重写架构或调试与资源管理相关的问题,并且您希望尽快将其启动,那么智能指针是可行的方法并且不会招致即使在大型游戏中也有明显的性能成本.

This has also significantly reduced the amount of time spent debugging and hunting down memory leaks. In theory, a well-designed application would never run into these problems. In real life working with deadlines, legacy systems, or existing game engines that were poorly designed, however, they are an inevitability on large projects like games... unless you use smart pointers. If you must dynamically allocate, don't have ample time for designing/rewriting the architecture or debugging problems related to resource management, and you want to get it off the ground as quickly as possible, smart pointers are the way to go and incur no noticeable performance cost even in large-scale games.

这篇关于为什么我不应该总是使用 shared_ptr 和 unique_ptr 而是使用普通指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆