具有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对象之外可见).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...