Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an std::array<T, 2> where T is non-copyable and non-default-constructible?

Tags:

c++

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?

like image 395
Joshua Chia Avatar asked Jul 29 '16 01:07

Joshua Chia


1 Answers

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'} }};

DEMO

like image 174
O'Neil Avatar answered Oct 13 '22 09:10

O'Neil