简体   繁体   中英

Class POD member variable initialization

Regarding the following two ways to initialize the POD member members variables:

class Trie {
  Trie()
    : isWord_(false)
  { }


  vector<Trie *> child(keyLength);
  bool isWord;
};

// OR 

class Trie {
  Trie();

  vector<Trie *> child(keyLength);
  bool isWord = false;
};

Are the two equivalent (performance wise, generated code size wise, etc)? Is there a current preference?

I would refer to this article Get to Know the New C++11 Initialization Forms for answers.

They are semantically equivalent, as the article states:

Regardless of the initialization form used, the compiler conceptually transforms every class member initializer into a corresponding mem-init

However there are some things that are allowed by second option which are impossible for first one if we go outside of POD scope. For example: array initialization.

As for current preference, there is always a strong argument of making Your code readable for others:

  • If You're working on a big project, stick to whatever form the rest of project follows, don't enforce new ideas where they're not wanted
  • If Your project is small, try to talk with other of its end-users to agree on common form if You think one is more readable than other.

My personal preference would still be first option, because with it I have all the information about class initialization in one place (the constructor) and don't have to scroll all the way to the bottom to see if someone suddenly made a default initialization there.

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