简体   繁体   中英

Should I always initialize every data member of a class in c++?

Is this a good practise,or it just depends?

Thanks.

The only time it might make sense not to initialize would be if you are going to default-construct large numbers of POD objects in performance-critical code and then populate them with valid data afterwards -- eg if you were going to create an array of one million objects, and then populate the array's objects with valid data. In that scenario you might want to avoid the initialization, since it's a waste of CPU cycles to zero everything out when you're only to overwrite it again afterwards.

But if you do that, be sure to put /* LOTS OF EYE-GRABBING COMMENTS */ in your class's .h file warning the user about what you are doing and why, and document it thoroughly in any other programmer's documentation you maintain. Tracking down uninitialized-value bugs isn't much fun...

The rule of thumb is an object should never exist in an uninitialized state. The only way to accomplish this is to initialize all member variables during construction. There is a difference between an object being in an uninitialized state and an invalid state. An uninitialized state occurs when member variables are not initialized object during construction. Since the variables likely contain unknown values any member function that relies on them may intermittently behave differently. An invalid state initializes the variables to default values providing some expectation the object will always behave the same after construction.

In the book: "Ruminations on C++" by Andrew Koenig and Barbara Moo, Chapter 4

Does every ctor need to init every data member? It's not always true, sometimes your data member has it's meaning when your object exsits for a while, it really depends.

The book I have is not the original English version, so I kind of translated it. If you want to know more, read the whole Chapter4:)

Never say always.

It is a very, very good pratice to initialize every data member. But sometimes, in very specific situations, you may need to skip some initialization if you are going to create a large amount of objects - which will take more CPU cycles than you would like - and you will initialize them later, and you can garantee that no data member will be ever used before initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM