jeudi 30 novembre 2017

Is it possible to remove dispatch_once in Objective-C++?

Since C++11, local static variables are known to be initialized in a thread safe manner (unless the -fno-threadsafe-statics is given), as specified in this question. Does that mean that the following well-known pattern:

+ (NSObject *)onlyOnce {
  static NSObject *object;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    object = [[NSObject alloc] init];
  });
  return object;
}

Can be replaced with the much shorter:

+ (NSObject *)onlyOnce {
  static NSObject *object = [[NSObject alloc] init];
  return object;
}

When compiling the code as Objective-C++ with C++ language dialect of C++11 and higher?

Aucun commentaire:

Enregistrer un commentaire