C ++ posting new and copying

I read somewhere that this vector internally uses the new placement to construct the object. When I tried to implement a container like this, I usually get a selection like

_elements = new Type[capacity]

and then add new objects like

void append(const T& element) {
    // reallocation in case if capacity is equal to size
    _elements[size++] = element;
}

      

Is there any performance or other difference between this construct by copying and constructing by placing a new one?

+3


source to share


1 answer


Is there any performance or other difference between this construct by copying and constructing by placing a new one?

Sure. If you construct an array:

_elements = new Type[capacity]

      

... then the elements of the array must be initialized, down to capacity. This means that several default objects will be created. On the other hand, when using a new placement, you are not initializing the array, but simply allocating space and building objects as needed. This is more efficient and semantically different since no initial objects are created (remember that creating them can have side effects).

This might help you understand and do some experimentation with the type, which does have a noticeable side effect in its default constructor:

class Type
{
    public:
    Type()
    {
       cout << "Created Type." << endl;
    }
};

      

With the above Type

, if you do new Type[3]

, for example, you will see three messages printed on cout

. On the other hand, if you create std::vector<Type>

with a capacity of 3, you should not see any messages printed on cout

.



Your add method:

void append(const T& element) {
    // reallocation in case if capacity is equal to size
    _elements[size++] = element;
}

      

Calls the assignment operator for T

. Therefore, adding an object to a container requires that:

  • The object is first created using the default constructor
  • The assignment operator is called

Contrast this with the standard library containers:

  • Objects are created using the copy constructor (and through the placement of `new ')
  • No appointment required.

Another consideration is that you usually cannot call new Type[x]

unless Type

you have a default constructor available. If you change to public:

in the example above private:

, you will notice it. It's still possible to create (empty) std::vector<Type>

, but you can still add objects to it as long as you add another (useful) constructor to Type

.

+9


source







All Articles