boost::shared_ptr in Objective-C++

2019-05-25 02:53发布

问题:

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?