Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this use of emplace_back with deleted copy constructor work?

Tags:

I have a type that I have deleted the copy constructor from, and I would like to have a vector of this type, so I need to create all the elements via emplace_back. But, emplace_back seems to require a copy constructor, as the compiler gives a warning about not being able to instantiate emplace_back because the copy constructor has been deleted. Why does it need a copy constructor? I thought the whole point of emplace_back was to build the vector without copying anything. Can I even have a vector of objects that don't have a copy constructor?

class MyType {
public:
    MyType(std::array<double, 6> a) {}
    MyType(const MyType& that) = delete;
};

int main() {
    std::vector<MyType> v;
    std::array<double, 6> a = {1,2,3,4,5,6};
    v.emplace_back(a);
}

Compiler is clang/llvm.

like image 950
Drew Avatar asked Dec 31 '15 09:12

Drew


1 Answers

When the vector's internal storage grows, it will need to move the elements from the old storage to the new. By deleting the copy constructor, you also prevent it generating the default move constructor.

like image 60
BoBTFish Avatar answered Nov 03 '22 01:11

BoBTFish