mardi 13 octobre 2020

Difference between brace initialization and copy initialization a dynamically allocated object

this one might be trivial, yet i could not name it properly hence i could not find an answer.

Is there any significant difference between 1 and 2 performance wise?

class Object {
  int number_;
  Object(int number) : number_(number) {}
};

// then, in main.

Object* objPtr1 = new Object(11) // nr.1
Object* objPtr2 {new Object{11}} // nr.2

From my understanding the only upside of 2 is that objPtr2 is directly initialized with the address of dynamically created object, so no copying involved.

On the other hand objPtr1 is being copy initialized, which means that:

  1. operator new returns an address of newly created object,
  2. the address is being copied to objPtr1.

This process involves unnecessary copying, which could be omitted by directly initializing (as in 2). If my understanding is correct, does it make much difference performance wise, to use 2 over 1?

Aucun commentaire:

Enregistrer un commentaire