Running work in a C init object

In C ++, doing heavy work in the constructor is not recommended, among other things, if an exception occurs after memory allocation, a memory leak may occur. In Java, it is still not recommended, but it is of less importance due to the garbage collector. In lens C, where is the init position for heavy lifting?

+4
source share
2 answers

The general guideline is that lazy loading is preferred for anything that is expensive. Generally speaking, init should avoid costly calls as you may not need results. Perhaps the caller creates this object and then discards it or looks at only one value. You would like to avoid creating massive data structures that are not needed. This guide should increase productivity; This is not a tough rule.

Valid, but rare, to allow init to fail and return nil . See here the bbum answer for the correct approach: Returning a null value in init in Objective-C code .

+3
source

In objetive-c template for initializer

 -(id)init { if (self = [super init]) { // Initialization code here } return self; } 

If the initializer does not work, it should return nil . This means that if your initializer fails, it must correctly release self to avoid leakage. Therefore, I think that you are safe if you follow the pattern.

 -(id)init { if (self = [super init]) { if (myInitializationFunc() == ERR_FAIL) { [self release]; return nil; } } return self; } 
+3
source

Source: https://habr.com/ru/post/1399437/


All Articles