views:

142

answers:

2

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?

+3  A: 

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

void no_destroy(MyCppObj*)
{}

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

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

MKroehnert
Then how do I pass this shared_ptr? I tried that and for some reason it failed.
John Smith
Add a method like this: "- (boost::shared_ptr<MyCppobj>) getCppobj {return cppobj;}" to the OCPP class and access the member cppobj through this method.Now the pointer belongs to the instance of OCPP and will only get deleted when this instance is deallocated.
MKroehnert