明确删除shared_ptr [英] Explicitly deleting a shared_ptr

查看:686
本文介绍了明确删除shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:是否允许您自己明确删除boost::shared_ptr?你应该吗?

Simple question here: are you allowed to explicitly delete a boost::shared_ptr yourself? Should you ever?

澄清,我并不是说删除shared_ptr持有的指针.我的意思是实际的shared_ptr本身.我知道大多数人建议不要这样做,所以我只是想知道是否可以明确地做到这一点.

Clarifying, I don't mean delete the pointer held by the shared_ptr. I meant the actual shared_ptr itself. I know most people suggest to not do it, so I was just wondering if it's OK to explicitly do it.

推荐答案

您的问题不清楚.如果动态分配了shared_ptr,则可以随时随地允许它delete.

Your question isn't clear. If you've allocated a shared_ptr dynamically then you're certainly allowed to delete it whenever you want.

但是,如果您要问是否允许删除shared_ptr管理的任何对象,那么答案取决于....如果shared_ptr::unique返回true,则调用shared_ptr::reset将删除托管对象.但是,如果shared_ptr::unique返回false,则意味着有多个shared_ptr共享该对象的所有权.在这种情况下,对reset的调用只会导致引用计数递减1,而当管理该对象的最后一个shared_ptr超出范围或本身成为reset时,将实际删除该对象.

But if you're asking whether you're allowed to delete whatever object is being managed by the shared_ptr, then the answer is ... it depends. If shared_ptr::unique returns true, then calling shared_ptr::reset will delete the managed object. However, if shared_ptr::unique returns false, it means there are more than one shared_ptrs sharing ownership of that object. In this case a call to reset will only result in the reference count being decremented by 1, actual deletion of the object will take place when the last shared_ptr managing that object either goes out of scope or is itself reset.


编辑后,似乎您正在询问要删除动态分配的shared_ptr.像这样:


After your edit, it seems you are asking about deleting a dynamically allocated shared_ptr. Something like this:

auto sp = new boost::shared_ptr<int>( new int(42) );

// do something with sp

delete sp;

这是允许的,并且可以按预期工作,尽管这将是一个不寻常的用例.唯一的警告是,如果在分配和删除sp之间创建另一个共享该对象所有权的shared_ptr,则删除sp不会导致对象的删除,只有在引用计数时才会发生该对象将变为0.

This is allowed and will work as expected, although it would be an unusual use case. The only caveat is that if in between the allocation and deletion of sp you create another shared_ptr that shares ownership of the object, deleting sp will not result in deletion of the object, that will only happen when the reference count for the object goes to 0.

这篇关于明确删除shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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