Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference type as instance variable in Objective-C++

C++ reference types as instance variables are forbidden in Objective-C++. How can I work around this?

like image 833
Karl von Moor Avatar asked Dec 23 '22 03:12

Karl von Moor


1 Answers

You can't sensibly use references as instance variable because there is no way to initialize instance variables and references can't be reseated.

An alternative might be to simply use (possibly smart) pointers instead.

Another possibility that gets you closer to C++-like behaviour is to use a PIMPL-style member for your C++ members:

struct CppImpl {
    SomeClass& ref;
    CppImpl(SomeClass& ref) : ref(ref) {}
};

@interface A : NSObject {
    CppImpl* pimpl;    
}
- (id)initWithRef:(SomeClass&)ref;
@end

@implementation    
- (id)initWithRef:(SomeClass&)ref {
    if(self = [super init]) {
        pimpl = new CppImpl(ref);
    }
    return self;
}
// clean up CppImpl in dealloc etc. ...
@end
like image 134
Georg Fritzsche Avatar answered Jan 22 '23 08:01

Georg Fritzsche