Initializing class members without a pointer

Recently, I read a lot about designers from the well-received C ++ FAQ . One entry mentions that it is always better to use initialization lists, as opposed to initializing class members in the code block of the constructor itself.

This is because the compiler tends to create multiple copies of class members, not just one copy.

Example

Good

Foo::Foo( void ) : mBar( new Bar ) //pointer to some memory address { } 

Bad

 Foo::Foo( void ) { mBar = new Bar; } 

One of them also indicates (and, although this also applies to constructors, it also refers to the clean initialization of objects in general from even non-member functions) is that when initializing an object using methods such as:

 void f( void ) { Foo foo( Bar() ); //Bad. foo.x(); //error } 

You, and I quote: "[declare] a non-member function that returns a Foo object" .

(for more information click the link above)

Question

Because of this, it is not wise to have the following:

 Geometry::Geometry( void ) : mFaces( QVector< GLushort >() ), mFinalized( false ), mNormals( QVector< QVector3D >() ), mVerticies( QVector< QVector3D >() ) 

Or even this:

 Geometry::Geometry( void ) : mFaces( QVector< GLushort > ), mFinalized( false ), mNormals( QVector< QVector3D > ), mVerticies( QVector< QVector3D > ) 

Due to how they are distributed (that is, that they are not pointers), this makes me wonder if these objects are needed even at the beginning of initialization. If so, is this the correct method? Or is there a better way to initialize?

How does this relate to the issue

This relates to the general question because the C ++ constructor initialization methodology relates both to the initialization of objects using constructor functions, and to the fact that I am not aware of whether objects were allocated on the stack or, I believe, that in any case (in any case, objects without a pointer) even initialization is needed .

+8
c ++ stack constructor initialization class-members
source share
1 answer

If a member variable has a class type with a default constructor declared by the user, you do not need to explicitly specify it in the initialization list: its default constructor will be called anyway during construction in front of the constructor body.

If a member variable is a primitive type (e.g. int or bool ) or has a class type that does not have any user-declared constructors, you need to initialize it explicitly, otherwise it will not be initialized (and it will have an unknown value, you will not can read the uninitialized object).

+12
source share

All Articles