Search code examples
c++c++11containersvalue-initialization

C++ value initialize items of a custom container


Lets take custom vector implementation as an example:

template<typename Object>
class myVector {
public:
    explicit myVector(int size = 0) :
        _size{ size },
        _capasity{ size + SPARE_CAPACITY }
    {
        _buff = new Object[_capasity];
        if (_size > 0) {
            for (int i = 0; i < _size; i++) {
                //_buff[i] = 0;
            }
        }
    }

// more code

private:
    Object * _buff = nullptr;
    int _size;
    int _capasity;
};

So my question is, how to make myVector be value-initialized in case I'll initialize it as:

int main() {
    myVector<int> v02(5);                   
}

Here, it contains 5 int values, so I need it to be all zeros; same with other types. I commented out _buff[i] = 0; as it's specific to int. Please give me some hints.


Solution

  • It's as simple as

    for (int i = 0; i < _size; i++)
        _buff[i] = Object{};
    

    Alternatively, you could get rid of the loop and add a pair of {} (or ()) here:

    _buff = new Object[_capasity]{};
    //                           ^^
    

    But this option would value-initialize all _capasity objects, rather than the first _size ones, as noted by @bipll.


    Also, note that if you want to mimic the behavior of std::vector, you need to allocate raw storate (probably std::aligned_storage) and call constructors (via placement-new) and destructors manually.

    If Object is a class type, _buff = new Object[_capasity]; calls default constructors for all _capasity objects, rather than for the first _size objects as std::vector does.