User account creation filtered due to spam.

Bug 32141 - default init doesn't work in ctor initializer list
Summary: default init doesn't work in ctor initializer list
Status: RESOLVED DUPLICATE of bug 30111
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.2.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2007-05-29 16:50 UTC by James Kanze
Modified: 2007-06-10 02:18 UTC (History)
4 users (show)

See Also:
Host: i686-pc-linux-gnu
Target: i686-pc-linux-gnu
Build: i686-pc-linux-gnu
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description James Kanze 2007-05-29 16:50:12 UTC
A POD struct is not correctly initialized when default
initialization is requested in the initialization list of a
constructor, and it is a base class.  Consider the following
program:

-------------------------------------------------

#include <iostream>
#include <memory>
#include <stdlib.h>
#include <string.h>

void*
operator new( size_t n ) throw (std::bad_alloc)
{
    void*               p = malloc( n ) ;
    if ( p == NULL ) {
        throw std::bad_alloc() ;
    }
    memset( p, 0xAA, n ) ;
    return p ;
}

void
operator delete( void* p ) throw ()
{
    free( p ) ;
}

struct POD
{
    short               l ;
    unsigned char       s[ 6 ] ;
} ;

class A : public POD
{
public:
    A() : POD() {}
} ;

class B
{
public:
    B() : myPOD() {}
    POD myPOD ;
} ;

int
main()
{
    A* pA = new A ;
    std::cout.setf( std::ios::hex, std::ios::basefield ) ;
    std::cout << "length A = " << pA->l << std::endl ;
    B* pB = new B ;
    std::cout << "length B = " << pB->myPOD.l << std::endl ;
    return 0 ;
}
-------------------------------------------------
(The replacement new and delete are just to ensure that the
memory doesn't accidentally happen to be correctly initialized.)

According to the standard, "An object whose initializer is an
empty set of parentheses, i.e., (), shall be
default-initialized", and default initialization of a POD type
is zero-initialization.  When compiled, however, this program
outputs:

-------------------------------------------------
length A = aaaa
length B = 0
-------------------------------------------------

The default initialization has correctly taken place for the
member object, but not for the base class.

-- 
James Kanze (GABI Software)             email:james.kanze@gmail.com
Conseils en informatique orientée objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Comment 1 Andrew Pinski 2007-06-10 02:18:49 UTC

*** This bug has been marked as a duplicate of 30111 ***