C++11 member initializer list vs in-class initializer?

前端 未结 3 1748
走了就别回头了
走了就别回头了 2020-11-30 19:48

What difference between these ways of initializing object member variables in C++11 ? Is there another way ? which way is better (performance) ?:

class any          


        
3条回答
  •  -上瘾入骨i
    2020-11-30 20:37

    They are the same.

    Neither is better than the other in terms of performance, and there is no other way to initialise them.

    The benefit of in-class initialisation (the first in your example) is that the order of initialisation is implicit. In initialiser list you have to explicitly state the order - and compilers will warn of out-of-order initialisation if you get the ordering incorrect.

    From the standard:

    12.6.2.5
    nonstatic data members shall be initialized in the order they were declared 
    in the class definition
    

    If you get the order wrong in your list, GCC will complain:

    main.cpp: In constructor 'C::C()':
    main.cpp:51:9: warning: 'C::b' will be initialized after
    main.cpp:51:6: warning:   'int C::a'
    

    The benefit of initialiser lists is perhaps a matter of taste - the list is explicit, typically in the source file. In-class is implicit (arguably), and is typically in the header file.

提交回复
热议问题