Home > Back-end > Ask questions about the class member variable initialization, the code is as follows:
Ask questions about the class member variable initialization, the code is as follows:
Time:10-08
Class A { Public: Char id [18]; Char name [40]. (A) { Memset (this, 0, sizeof (A)); } ~ (A) { } . Other member function . }
Class B { Public: A, A. Double x; Char Filename [256].
(B) { Memset (this, 0, sizeof (B)); } ~ (B) { } . Other member function . }
Class C { Public: A, A. Double x; Char Filename [256]. The init () { Memset (this, 0, sizeof (C)); } (C) { The init (); } ~ (C) { } . Other member function . } Consult the initialization is correct, class B and class C initialization what's the difference? Can you use that? Why is that?
CodePudding user response:
(A) {memset (this, 0, sizeof (A)); } as the initialization list: (A) : id (0), name (0) {}
Memset needless to write initialization code, are the benefits of simple 0, A problem is platform compatibility, not all platform compiler support memset, The other is a performance issue, memset is a system call, the system call is not fast, Again, some members can't simply clear 0, be careful, otherwise an error,
Initialization list is used in c + +, can get good optimization, write code that is more,
You the code above, under the system of inheritance, more than just calls the memset. Initialize the way to class B and C is the same, B initialization process: member a initialization, call memset part B constructor calls memset repeat again set memory is 0, inefficient, Although efficiency is lower, but such use is possible, this pointer is still effective under the constructor, since it is first allocates memory, executive member of the initialization (so the initialization list ways can get the best optimization), then implement the constructor,
CodePudding user response:
Memset (this, 0, sizeof (C)); This code will only in some cases no problem,
Each member of the array class honestly use memset