【问题标题】:std::unique_ptr as a @property in objective cstd::unique_ptr 作为目标 c 中的 @property
【发布时间】:2015-06-30 04:45:53
【问题描述】:

如何在目标 c 类的接口部分定义 std::unique_ptr 的@property?

@property std::unique_ptr<MyClass> ptr;

但是我可以定义一个共享指针!

如果我定义了唯一指针,那么我得到的错误是:

不能赋值,因为它的复制赋值运算符是 隐式删除

【问题讨论】:

  • 通过这个link
  • 谢谢..我做到了..我一般可以使用智能指针,但是当我在接口部分使用 unique 作为属性时,我得到了这个错误..即使我把它用作变量它工作正常..

标签: ios objective-c shared-ptr unique-ptr


【解决方案1】:

属性综合是这里的罪魁祸首。当您声明 @property unique_ptr&lt;MyClass&gt; 时,编译器会隐式创建 setter 和 getter 函数以及一个支持变量。

set 函数可能看起来像这样:

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

set 函数中的那一行调用 std::unique_ptr 的复制赋值运算符,该运算符被有意删除,因为 std::unique_ptr 使用移动语义。请记住,您不能复制 unique_ptr,您只能将所有权从一个实例转移到另一个实例。

要解决这个问题,您需要定义自己的集合并获取尊重移动语义的函数,或者您需要直接使用 ivar。

这是一个可以正常工作的示例集函数。

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

【讨论】:

    【解决方案2】:

    作为 Ref[1],编译器将为 @property 生成 setter、getter 和实例变量。


    以下是编译无误的例子:

    // .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
    
    

    注意:

    unique_ptr 应该用在 Objective-C 类的内部并且不应该用 unique_ptr 类型。

    “幸运的是,编译器会阻止你做一些愚蠢的事情,比如用 std::unique_ptr 声明 @property。如果没有,那么当你第一次使用 self.foo 访问该值时,你的类将失去对指针。”参考[2]


    参考
    1. 使用 Xcode 4.4 自动进行属性合成
      https://useyourloaf.com/blog/property-synthesis-with-xcode-4-dot-4/

    2. Objective C,编码和你
      https://medium.com/@dmaclach/objective-c-encoding-and-you-866624cc02de

    【讨论】:

      猜你喜欢
      • 2016-03-31
      • 2019-02-06
      • 2014-03-27
      • 2011-01-23
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多