gpt4 book ai didi

c++ - 我应该使用 shared_ptr 还是 unique_ptr

转载 作者:IT老高 更新时间:2023-10-28 14:01:32 26 4
gpt4 key购买 nike

我一直在使用 pimpl 成语制作一些对象,但我不确定是否使用 std::shared_ptrstd::unique_ptr .

我知道 std::unique_ptr 效率更高,但这对我来说不是什么大问题,因为这些对象无论如何都相对重量级,所以 std 的成本: :shared_ptr 而不是 std::unique_ptr 相对较小。

我目前使用 std::shared_ptr 只是因为它具有额外的灵 active 。例如,使用 std::shared_ptr 允许我将这些对象存储在 hashmap 中以便快速访问,同时仍然能够将这些对象的拷贝返回给调用者(因为我相信任何迭代器或引用可能很快无效)。

但是,这些对象实际上并没有被复制,因为更改会影响所有拷贝,所以我想知道也许使用 std::shared_ptr 并允许复制是某种反模式或坏事。

这对吗?

最佳答案

I've been making some objects using the pimpl idiom, but I'm not sure whether to used shared_ptr or unique_ptr.

绝对是 unique_ptrscoped_ptr

Pimpl 不是一种模式,而是一种习语,它处理编译时依赖和二进制兼容性。它不应影响对象的语义,尤其是在其复制行为方面。

您可以在后台使用您想要的任何类型的智能指针,但是这两个保证您不会意外地在两个不同的对象之间共享实现,因为它们需要有意识地决定复制构造函数的实现和赋值运算符。

However, these objects in a way really aren't being copied, as changes affect all copies, so I was wondering that perhaps using shared_ptr and allowing copies is some sort of anti-pattern or bad thing.

它不是反模式,实际上是一种模式:别名。您已经在 C++ 中使用了它,并带有裸指针和引用。 shared_ptr 提供了一种额外的“安全性”措施来避免死引用,但代价是额外的复杂性和新问题(注意会造成内存泄漏的循环)。


与 Pimpl 无关

I understand unique_ptr is more efficient, but this isn't so much of an issue for me, as these objects are relatively heavyweight anyway so the cost of shared_ptr over unique_ptr is relatively minor.

如果您可以排除某些状态,您可能需要查看 Flyweight模式。

关于c++ - 我应该使用 shared_ptr 还是 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576922/

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