views:

114

answers:

2

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

A: 

boost::ref() may help?

Noah Roberts
Not really - `reference_wrapper<T>` has no default constructor and you can't initialize instance variables.
Georg Fritzsche
+4  A: 

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
Georg Fritzsche
yeah, that's it!
Polybos