initializing

hi guys.

sth is in my mind.

fast way of initializing an object through constructer is
Fred::Fred() : x_(whatever) { }

slow way
Fred::Fred() { x_ = whatever; }

ok. i accept it is faster but why?? what is the difference compiler does.

i would like to make a googling but i dont know what to search :( sorry
Whatever you do, x_ is initialized before the opening brace. In the first case, it is initialized by the constructor that takes whatever, in the second case it is initialized by the default constructor.

Additionally in the second case, you're throwing away the results of initializating by using assignment.

(of course, if the type of x_ is non-class (e.g. int or double), default initialization is a no-op, and the two cases are functionally equivalent)
Last edited on
hmmm thx @Cubbi that was quite informative. and also it will take a little time for me to understand fully :D
Last edited on
There is a reasonable case for preferring
Fred::Fred() { x_ = whatever ; } over
Fred::Fred() : x_(whatever) { }
for trivially default-constructible and and trivially-copyable types (for instance double).

1
2
3
4
5
6
7
struct A
{
     explicit( int v ) : j(v+1), i(j+1) {} // bad, unintuitive; i is initialized before j
                    // change the order of declaration of i and j and meaning changes
     int i ;
     int j ;
}



If x_ is of a type that is not default-constructible or not assignable, (for inatance a const int)this does not work at all:
1
2
 Fred::Fred() // *** error: const int is not default-constructible
{ x_ = whatever ; }// *** error: can't assign to const int 
Last edited on
(if i did not misunderstand) there is no value assigned to variable in the first method.

but what if after a load like mySurface = SDL_LoadBMP("someimage.bmp"); this, i need to make a check if the image really loaded or not.

i used to use mySurface == NULL. but what will i use now to check???
Last edited on
Something like this? (tentative, based on a very quick glance at the SDL documentation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <memory>

struct A
{
    explicit A( const char* path = "someimage.bmp" )
                                 : my_surface( SDL_LoadBMP(path), &SDL_FreeSurface )
    {
        if( !my_surface )
        {
            // error; may be throw something
        }
    }

    private: std::unique_ptr< SDL_Surface, decltype(&SDL_FreeSurface) > my_surface ;
};
ohhh. thx @JLBorges.

that was hell helpful
Topic archived. No new replies allowed.