微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有ARC的结构中的Objective-C类

我尝试使用类中的类创建一个结构体:
struct my_struct
{
    Nsstring *string;
    // more fields
};

令我吃惊的是,Objective-C允许使用ARC.
它将如何管理字符串?
它可以容易地保留在每个作业中,但释放是问题.
它可以在其中添加一个析构函数,但这会使结构非常简单.
它也可以使其不保留或释放,但是要做到这一点应该是unsafe_unretained.

从我的观察,使用这个没有什么崩溃,但我想知道这里真正发生了什么.

解决方法

4.3.5 of the ARC docs

4.3.5. Ownership-qualified fields of structs and unions

A program is ill-formed if it declares a member of a C struct or union
to have a nontrivially ownership-qualified type.

Rationale: the resulting type would be non-POD in the C++ sense,but C
does not give us very good language tools for managing the lifetime of
aggregates,so it is more convenient to simply forbid them. It is
still possible to manage this with a void* or an __unsafe_unretained
object.

This restriction does not apply in Objective-C++. However,nontrivally
ownership-qualified types are considered non-POD: in C++11 terms,they
are not trivially default constructible,copy constructible,move
constructible,copy assignable,move assignable,or destructible. It
is a violation of C++’s One DeFinition Rule to use a class outside of
ARC that,under ARC,would have a nontrivially ownership-qualified
member.

Rationale: unlike in C,we can express all the necessary ARC semantics
for ownership-qualified subobjects as suboperations of the (default)
special member functions for the class. These functions then become
non-trivial. This has the non-obvIoUs result that the class will have
a non-trivial copy constructor and non-trivial destructor; if this
would not normally be true outside of ARC,objects of the type will be
passed and returned in an ABI-incompatible manner.

如果您阅读所有注意事项,我强烈建议您不要在ObjC中进行此操作.我强烈建议在任何情况下不要广泛使用ObjC.这是一种桥梁语言,可以帮助纯粹的ObjC和纯C谈话.它有很多问题.将ObjC与ARC相结合,引入了ObjC中不会发生的时间和空间性能成本,从而使其异常安全.定义这些类型的ObjC特定的数据结构使得很难与非ObjC代码和非ARC代码进行交互(请注意,您不能在ARC之外使用此注意事项).您应该从ARC中免费获得的大部分突然变得很难,因为您必须再次担心内存管理(正如您已经发现的那样).

构建纯ObjC层.构建一个纯C层.构建一个薄的ObjC层来将两者结合在一起.不要将ObjC对象放在结构体中,绝对不会在任何公共结构体中(即在定义它的单个ObjC对象之外可见).

原文地址:https://www.jb51.cc/c/114433.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐