boost::shared_ptr in Objective-C++

依然范特西╮ 提交于 2020-01-02 09:27:23

问题


This is a better understanding of a question I had earlier.

I have the following Objective-C++ object

@interface OCPP
{
    MyCppobj * cppobj; 
}
@end

@implementation OCPP

-(OCPP *) init
 {
   cppobj = new MyCppobj;
 }
 @end

Then I create a completely differently obj which needs to use cppobj in a boost::shared_ptr (I have no choice in this matter, it's part of a huge library which I cannot change)

@interface NOBJ
-(void) use_cppobj_as_shared_ptr
{
    //get an OCPP obj called occ from somewhere..
    //troubling line here
}
@end

I have tried the following and that failed: I tried synthesising cppobj. Then I created a shared_ptr in "troubling line" in the following way:

MyCppobj * cpp = [occ cppobj];
bsp = boost::shared_ptr<MyCppobj>(cpp);

It works fine first time around. Then I destroy the NOBJ and recreate it. When I for cppobj it's gone. Presumably shared_ptr decided it's no longer needed and did away with it.

So I need help. How can I keep cppobj alive?

Is there a way to destroy bsp (or it's reference to cppobj) without destroying cppobj?


回答1:


shared_ptr supports custom deallocators. What you can do, is, do nothing.

void no_destroy(MyCppObj*)
{}

bsp = boost::shared_ptr<MyCppObj>(cpp, &no_destroy);



回答2:


Why not use boost::shared_ptr<MyCppObj> cppobj; in OCPP instead of MyCppobj * cppobj; to store the instance of MyCppObj?



来源:https://stackoverflow.com/questions/2679967/boostshared-ptr-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!