将unique_ptr传递给函数 [英] Passing unique_ptr to functions
问题描述
我想现代化一些现有的代码。
- 我有一个类,目前有一个成员变量Device * device_。
- 它使用new在一些初始化代码中创建一个实例,并在destructory中有一个delete device_。
- 此类别的成员函数调用其他以Device *作为参数的函数。
这很好,但是为了现代化我的代码我想我应该更改变量定义为std :: unique_ptr< Device> device _
并删除显式调用删除,这使代码更安全,一般更好。
我的问题是这个 -
- 我应该如何将 device _变量传递给需要它作为参数的所有函数?
我可以调用.get获取每个函数调用中的原始指针。但这看起来很丑陋,浪费了使用unique_ptr的一些原因。
或者我可以改变每个采用类型Device *的参数,它现在采用类型std :: unique_ptr&的参数。其中(对我来说)有些混淆了函数原型,并使它们很难阅读。
这是什么最好的做法?
在现代 C ++风格中,有两个关键的概念:- 所有权
- 无效
所有权是关于某个对象/资源(在这种情况下是 Device
的实例)的所有者。各种 std :: unique_ptr
, boost :: scoped_ptr
或 std :: shared_ptr
是关于所有权的。
你是 >将你的类的实现移动到 这清楚地表明,你的类是这个内存的唯一负责人,整洁地处理记忆可能泄漏的各种方式。 另一方面,资源的大多数用户不太在意它的所有权。 只要函数不保存对对象的引用(将其存储在映射或其他对象中),那么所有重要的是对象的生命周期超过函数调用的持续时间。 因此,选择如何传递参数取决于其可能的无效: I'm trying to "modernize" some existing code. This works well, but to "modernize" my code I thought I ought to change the variable to be defined as My question is this - I can call .get to get the raw pointer in each function call. But that seems ugly and wastes some of the reasons to use a unique_ptr in the first place. Or I can change every function so that instead of taking a parameter of type "Device*" it now takes a paramater of type "std::unique_ptr& ". Which (to me) somewhat obfuscates the function prototypes, and makes them hard to read. What is best practice for this? Have I missed any other options? In Modern C++ style, there are two keys concepts: Ownership is about the owner of some object/resource (in this case, an instance of Nullity is much more simple however: it just expresses whether or not a given object might be null, and does not care about anything else, and certainly not about ownership! You were right to move the implementation of your class toward This clearly conveys that your class is the sole responsible for this piece of memory and neatly deals with all the various ways memory could have leaked otherwise. On the other hand, most users of the resources could not care less about its ownership. As long as a function does not keep a reference to an object (store it in a map or something), then all that matters is that the lifetime of the object exceeds the duration of the function call. Thus, choosing how to pass the parameter depends on its possible Nullity: 这篇关于将unique_ptr传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! unique_ptr
(一般来说),尽管如果你的目标是实现一个PIMPL,你可能想要一个具有深度复制语义的智能指针。 p>
"std::unique_ptr<Device> device_"
and remove the explicit call to delete, which makes the code safer and generally better.
Device
). The various std::unique_ptr
, boost::scoped_ptr
or std::shared_ptr
are about ownership.
unique_ptr
(in general), though you may want a smart pointer with deep copy semantics if your goal is to implement a PIMPL.