如何将shared_ptr传递给具有较低生存期的类? [英] How to pass shared_ptr to class with lower lifetime?

查看:55
本文介绍了如何将shared_ptr传递给具有较低生存期的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优化我的代码.我有一个具有shared_ptr数据成员的类.在此类的某些方法中,我创建了需要使用该成员的对象(只是从shared_ptr指向的对象中获取信息).我知道这些创建的对象的生命周期比我的主类要短.如何传递该指针?我认为不需要另一个shared_ptrs(因为我保证该对象将存在).那么,应该如何创建我创建的类?他们应该得到原始指针吗?Weak_ptr?还是最好的解决方案是获取shared_ptr(并增加其参考计数器)?什么是最标准的解决方案?

I'd like to optimize my code. I have one class that has a shared_ptr data member. In some methods of this class, I create objects that need to use this member (just to get information from the object pointed by shared_ptr). I know that lifetime of these created objects is lower than in my main class. How to pass this pointer? I think another shared_ptrs is unnecessary (because I have a warranty that the object will exist). So what should get my created classes? Should they get raw pointer? Weak_ptr? Or the best solution is getting shared_ptr (and incrementing its reference counter)? What is the most standard solution?

推荐答案

在这种情况下,当您知道时,共享资源的生存期将超过将指针传递给正确要做的是传递 reference raw指针:

In this case when you know the life-time of your shared resource will outlive those that you pass the pointer to the correct thing to do is pass a reference or a raw pointer:

void func(object* o)
{
    // do stuff with o
} 

// ...

std::shared_ptr<object> sp;

// ...

func(sp.get()); // pass raw pointer

这样做的主要原因是,不管管理资源的是哪种智能指针,该函数都是有用的.通过接受 raw指针,您的函数就可以接受来自共享指针以及唯一指针和任何其他第三方 smart的对象指针.

The main reason for this is that the function can be useful no matter what kind of smart pointer is managing the resource. By accepting the raw pointer your function is able to accept objects from shared pointers as well as unique pointers and any other third party smart pointer.

除非函数需要修改智能指针本身,否则传递智能指针没有任何好处.

There is no benefit to passing in the smart pointer unless the function needs to modify the smart pointer itself.

由Bjarne Straustrup& amp; amp; amp;可以在以下位置找到Herb Sutter: CppCoreGuidelines

A good set of guidelines being produced by Bjarne Straustrup & Herb Sutter can be found here: CppCoreGuidelines

有关传递原始指针(或引用)的规则:

The rule about passing raw pointers (or references): F.7

传递智能指针可转移或共享所有权,并且仅在打算使用所有权语义时才应使用.不影响生命周期的函数应改用原始指针或引用.

Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended. A function that does not manipulate lifetime should take raw pointers or references instead.

通过智能指针传递将功能的使用限制为使用智能指针的调用者.需要窗口小部件的功能应该能够接受任何窗口小部件对象,而不仅仅是可以通过特定类型的智能指针管理其寿命的窗口小部件.

Passing by smart pointer restricts the use of a function to callers that use smart pointers. A function that needs a widget should be able to accept any widget object, not just ones whose lifetimes are managed by a particular kind of smart pointer.

这篇关于如何将shared_ptr传递给具有较低生存期的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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