I have a fixed number of objects of class T that are non-copyable and non-default-constructible. Since the size is fixed I would like to use an array-ish container like std::array
instead of unique_ptr
or vector
. I would like to avoid the additional layer of indirection if I can help it.
How do I initialize an std::array<T, 2>
? Using array<T, 2> {T(...), T(...)}
results in an error about deleted copy constructor. Using array<T, 2> {move(T(...)), move(T(...))}
does not force the array elements to use the move constructor. If std::array<T, 2>
inherently does not work, what else can I do without resorting to an additional layer of indirection or manual memory management techniques like placement-new?
No need for extra stuff, just initialize it directly:
class Foo {
public:
Foo() = delete;
Foo(int,char) {}
Foo(Foo const &) = delete;
Foo & operator = (Foo const &) = delete;
};
std::array<Foo, 2> arr {{ {1, '1'}, {2, '2'} }};
My example is not the best but it works.. Just create a function that make_array
and have it create the instances for you..
#include <array>
#include <iostream>
class Foo
{
public:
Foo(int)
{
}
Foo(const Foo &) = delete;
Foo(Foo &&)
{
std::cout<<"Moved\n";
}
};
template<class... Type>
constexpr std::array<typename std::common_type<Type...>::type, sizeof...(Type)> make_array(Type&&... t)
{
return {std::forward<Type>(t)...};
}
int main() {
auto arr = make_array(Foo{1}, Foo{2});
return 0;
}
As pointed out in the comments, you can do std::array<Foo, 2> arr = {Foo{1}, Foo{2}}
.
I noticed you were trying to move
in your post. Are you sure your class is moveable
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.