1

I have a structure containing some data, especially big statically allocated array. The array length is not always completely used.

I need to do very often a copy of this data (in a realtime loop), so I need it to be as efficient as possible. Therefore, I want to copy only the length of the array that contains useful data.

Following is my suggestion for an assignment operator override. Could you please elaborate on the efficiency of it, and compare with for example the copy-and-swap idiom that I do not quite understand (What is the copy-and-swap idiom?).

struct Config
{
    // Assignment operator: Copy all data from other instance
    Config& operator=(const Config&obj)
    {
        currentArrayLength = obj.currentArrayLength;
        memcpy(array, obj.array, obj.currentArrayLength * sizeof(array[0]));
        return *this;
    }
    /* Static */
    static const size_t arrayLengthMax = 1000;
    /* Data */
    uint32_t currentArrayLength = 0;
    int32_t array[arrayLengthMax];
}
Community
  • 1
  • 1
Axel Williot
  • 485
  • 6
  • 13

1 Answers1

1

The copy-and-swap idiom generally means that you take the parameter obj by value, which means that it is implicitly copied by the copy constructor. The advantage is that you don't need to implement the copy logic in two places, but only in the copy constructor (the DRY participle: don't repeat yourself). You then swap the internal data of obj and this, and the old data is automatically destructed when the by value copy goes out of scope.

This can be done without performance loss for objects which manage dynamic data, because the swap is very cheap for those, but as your array is taking space in the object itself, your current implementation is faster – about as fast as it gets.

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131