什么时候删除了std :: shared

编程入门 行业动态 更新时间:2024-10-25 20:29:42
本文介绍了什么时候删除了std :: shared_ptr指向的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的图书馆中,我使用std:shared_ptr`s来保存我正在使用的通信对象。我有创建这些指针的模板函数。它返回原始指针,因此应用程序可以使用这些对象,而无需进行引用计数(严格的实时应用程序)。

In my library, I use std:shared_ptr`s to hold communication objects, I am working with. I have template function creating those pointers. It returns raw pointers so application could use those objects, without overhead with reference counting (strict realtime application).

template<typename COBTYPE> inline COBTYPE* CLink::createCob(COBTYPE cob) { std::shared_ptr<CCob> c(cob); if(c->init(this)!=OK){ trace(ERROR,"Cannot add cob, failed to initialize\n"); return NULL; } mCobs.push_back(c); //vector of my pointers return (COBTYPE*) c.get(); }

如果我调用函数,我不确定何时删除对象作为 link.createCob(new CobOfSomeTypo cob())吗? 当必须从堆栈中弹出时,使用shared_ptr可以防止删除cob对象吗?

I am in doubt, when the object will be deleted, if I call function as link.createCob(new CobOfSomeTypo cob()) ? Will use of shared_ptr prevent delete of cob object when it will have to pop from stack?

这个概念好吗?

推荐答案

当不再有共享指针共享所有权时,将删除共享指针共享所有权的对象

The object of which a shared pointer shares ownership is deleted when there are no more shared pointers sharing ownership, e.g. typically in the destructor of some shared pointer (but also in an assignment, or upon explicit reset).

(请注意,可能存在许多不同的共享指针类型共享同一对象的所有权!)

(Note that there may be shared pointers of many different types sharing ownership of the same object!)

也就是说,您的代码有问题。也许这样更好:

That said, your code has issues. Perhaps it might be better like this:

// Requirement: C must be convertible to CCob template <typename C> C * CLink::createCob() { auto p = std::make_shared<C>(); if (p->init(this) != OK) { return nullptr; } mCobs.push_back(std::move(p)); return mCobs.back().get(); }

用法如下: link.createCob< CobOfSomeTypo>()。不过,这取决于您是否需要获得现有指针的所有权。

The usage would then be: link.createCob<CobOfSomeTypo>(). It depends, though, on whether you need to be able to take ownership of existing pointers. That itself would be something worth fixing, though.

也有可能(但无法从您的问题中得知)您实际上根本不需要共享指针,并且可以简单地工作具有唯一的指针。

It's also possible (but impossible to tell from your question) that you dont actually need shared pointers at all and could simply work with unique pointers.

更多推荐

什么时候删除了std :: shared

本文发布于:2023-07-30 00:23:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   std   shared

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!