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.
It's as simple as
Alternatively, you could get rid of the loop and add a pair of
{}(or()) here:But this option would value-initialize all
_capasityobjects, rather than the first_sizeones, as noted by @bipll.Also, note that if you want to mimic the behavior of
std::vector, you need to allocate raw storate (probablystd::aligned_storage) and call constructors (via placement-new) and destructors manually.If
Objectis a class type,_buff = new Object[_capasity];calls default constructors for all_capasityobjects, rather than for the first_sizeobjects asstd::vectordoes.