c++ - 2 statements creating objects with regular new expression, any difference? -


consider following class user-defined default ctor.

class testclass { public:     testclass()     :data_(999) {     }     double getdata() const {         return data_;     }  private:     double data_; }; 

then create objects:

testclass *p2 = new testclass(); testclass *p1 = new testclass; 

any difference using 2 statements above in condition?

thank you,

short answer: no difference.

longer answer: §5.3.4,15 states that

a new-expression creates object of type t initializes object follows:
— if new-initializer omitted, object default-initialized (§8.5); if no initialization performed, object has indeterminate value.
— otherwise, new-initializer interpreted according initialization rules of §8.5 direct-initialization.

and §8.5,16 says

if initializer (), object value-initialized.

now value-initialization , default-initialization, defined §8.5,5-7:

to zero-initialize object or reference of type t means:
if t scalar type (3.9), object set value 0 (zero), [...]
— if t (possibly cv-qualified) non-union class type, each non-static data member , each base-class subobject zero-initialized , padding initialized 0 bits;
— if t (possibly cv-qualified) union type, object’s first non-static named data member zeroinitialized , padding initialized 0 bits;
— if t array type, each element zero-initialized;
— if t reference type, no initialization performed.

to default-initialize object of type t means:
if t (possibly cv-qualified) class type (clause 9), default constructor t called [...]
— if t array type, each element default-initialized;
otherwise, no initialization performed. [...]

to value-initialize object of type t means:
if t (possibly cv-qualified) class type (clause 9) user-provided constructor (12.1), default constructor t called [...]
— if t (possibly cv-qualified) non-union class type without user-provided constructor, object zero-initialized and, if t’s implicitly-declared default constructor non-trivial, constructor called.
— if t array type, each element value-initialized;
otherwise, object zero-initialized.

(emphasis mine)

together, since class has user provided default constructor, value initialization , default initialization same, both new expressions give same behavior, namely default constructor called.

it different thing e.g. ints:

int *p2 = new int(); // value-initialized, i.e. zero-initialized, *p2 0 int *p1 = new int;   // default-initialized, i.e. no initialization. *p1 garbage. or whatever. 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -