Viridya Viridya - 1 month ago 10
C++ Question

Fill vector with constructor call

I have two classes, one derive from the other.
I would like to allocate an

which is fill of the derived class.
The tricky question is that I want it to call the move constructor written in the base class.

Here is the code (I use c++11):

class Base{
size_t size;
double* buff;

Base(size_t _size):size(_size){
buff = new double[size];

Base() = delete;
Base operator=(const Base&) = delete;
Base(const Base&) = delete;

Base(Base&& b):size(b.size), buff(b.buff){
b.buff = nullptr;
Base operator=(Base&& b){
size = b.size;
buff = b.buff;
b.buff = nullptr;

class Derive : public Base{
Derive(size_t _size):Base(_size){};
Derive() = delete;
Derive operator=(const Derive&) = delete;
Derive(const Derive&) = delete;

Derive(Derive&& b):Base(move(b)){}
Derive operator=(Derive&& b){


vector<Derive> v(10, move(Derive(5)));

g++ is telling me
error: use of deleted function ‘Derive::Derive(const Derive&)’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
and I don't understand what I am supposed to do ...

Answer Source

The problem here is that std::vector(count, object) copies object, count times, into the vector. You cannot move from it since you can only move an object into a single object.

If your class is not copyable then you will not be able to use it. You can however use

std::vector<Type> foo;
for (int i = 0; i < count; ++i)