Std :: unique_ptr as @property in object c

How can I determine @property from std :: unique_ptr in front end of object class c?

@property std::unique_ptr<MyClass> ptr;

      

But I can define a generic pointer!

If I define a unique pointer, then I got the error:

cannot be assigned because of its copy assignment operator is implicitly removed

+3


source to share


2 answers


Here the synthesis of properties is synthesized. When declared @property unique_ptr<MyClass>

, the compiler implicitly creates-accessors for the function, along with the stem variable.

The set function probably looks something like this:

-(void) setPtr:(std::unique_ptr<MyClass>)ptr {
    _ptr = ptr;
}

      

This line in the set function calls the std :: unique_ptr copy assignment operator, which is intentionally removed because std :: unique_ptr uses move semantics. Remember that you cannot copy unique_ptr, you can only transfer property from one instance to another.



To work around this issue, you either need to define your own set, or get functions that respect move semantics, or you need to work with ivar directly.

Here is an example of a dial function that will work correctly.

-(void) setPtr:(std::unique_ptr<MyClass>)ptr {
    _ptr = std::move(ptr);
}

      

+2


source


As in [1], the compiler will generate a setter, getter and instance variable for @property.


Below is an example that compiles without error:

// .h file
@interface IOCMixCpp : NSObject
{
    std::unique_ptr<int> mTotal;
}

@property (nonatomic, readonly, assign) std::unique_ptr<int> total;

@end


      

// .mm file
@implementation IOCMixCpp

- (instancetype)init {
    self = [super init];
    if (self) {
        mTotal = std::make_unique<int>(9);
    }

    return self;
}

- (void)setTotal:(std::unique_ptr<int>)total {
    mTotal = std::move(total);
}

- (std::unique_ptr<int>)total {
// This line is error free.
    return std::move(mTotal);

// There is an error in the following line:
// Error: Call to implicitly-deleted copy constructor of 'std::unique_ptr<int>'
//    return mTotal;
}

@end


      



Note:

unique_ptr MUST be used in an internal Objective-C class and MUST NOT declare a property with type unique_ptr.

"Fortunately, the compiler won't let you do something stupid, like declaring @property with std :: unique_ptr. If it doesn't, the first time you access the value with self.foo, your class will lose ownership of the pointer." Link [2]


Link

  1. Automatic synthesis of properties since Xcode 4.4
    https://useyourloaf.com/blog/property-synthesis-with-xcode-4-dot-4/

  2. Objective C, Encoding and You
    https://medium.com/@dmaclach/objective-c-encoding-and-you-866624cc02de

0


source







All Articles