I'm trying to create an array of classes that can't be copied or moved. So I need to create the objects in-place and I can't figure out how to do that:
#include <vector>
struct Foo {
Foo(int) { }
Foo(const Foo &) = delete;
Foo & operator =(const Foo &) = delete;
Foo(Foo &&) = delete;
Foo & operator =(Foo &&) = delete;
};
struct Bla {
Bla(const std::vector<int> & args) {
for (auto i : args) {
foo.emplace_back(i);
}
}
std::vector<Foo> foo;
};
The compiler complains about the deleted move constructor because it's not guaranteed that all objects are constructed in-place and never moved. I don't have to use std::vector
as container, so feel free to suggest something else.
You can use std::vector
s iterator pair constructor to construct the objects like
Bla(const std::vector<int> & args)
: foo(args.begin(), args.end())
{}
If you have additional parameters that you need to include in the construction then you can switch to any of the node based containers like std::list
struct Bla {
Bla(const std::vector<int> & args) {
for (auto i : args) {
foo.emplace_back(i, some_other_argument);
}
}
std::list<Foo> foo;
};