[英]Do I need to memset a C struct in Swift?
AFAIK, In swift, calling the default initialiser of classes/structs will initialise everything to 0
, nil
. AFAIK,在 swift 中,调用类/结构的默认初始化程序会将所有内容初始化为
0
, nil
。 In C (socket programming for example) sometimes memset is used to set everything to 0 before using the struct.在 C(例如套接字编程)中,有时在使用结构体之前使用 memset 将所有内容设置为 0。 Do I need to use memset in swift too or is fine the way I wrote it?
我是否也需要在 swift 中使用 memset 还是我写的方式很好?
(BTW, In this case memset
is used because hints
should be set to 0 except below 2 parameters. Non 0 (garbage, etc) will have side effects on res
when calling getaddrinfo
. (顺便说一句,在这种情况下,使用
memset
是因为除以下 2 个参数外, hints
应设置为 0。非 0(垃圾等)将在调用getaddrinfo
时对res
产生副作用。
struct addrinfo hints, *res;
int status;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(NULL, MYPORT, &hints, &res);
var res = UnsafeMutablePointer<addrinfo>()
var hints = addrinfo()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
let status = getaddrinfo(nil, MYPORT, &hints, &res)
From the Xcode 6.3 release notes :来自Xcode 6.3 发行说明:
Imported C structs now have a default initializer in Swift that initializes all of the struct's fields to zero.
导入的 C 结构现在在 Swift 中有一个默认初始化器,可以将结构的所有字段初始化为零。
which means that意思就是
var hints = addrinfo()
initializes all fields of struct addrinfo
to zero and there is no need to call memset()
.将
struct addrinfo
所有字段初始化为零,无需调用memset()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.