happyloman
happyloman

Reputation: 21

initialize static array of objects c++

How do I declare an array of "Database" objects (no dynamic memory) for the following class?

class DataBase
{
 public: 
      DataBase(int code);
 private:
      Database();
      Database(const Database &);
      Database &operator=(const Database &);
 };

Upvotes: 0

Views: 2565

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476940

In C++17 and beyond, either like this:

Database a[] = { 1, 2, 3 };

Or with explicit constructors:

Database a[] = { Database(1), Database(2), Database(3) };

Pre-C++17, you could try something like this:

#include <type_traits>

std::aligned_storage<3 * sizeof(DataBase), alignof(DataBase)>::type db_storage;
DataBase* db_ptr = reinterpret_cast<DataBase*>(&db_storage);

new (db_ptr + 0) DataBase(1);
new (db_ptr + 1) DataBase(2);
new (db_ptr + 2) DataBase(3);

Now you can use db_ptr[0] etc. This isn't entirely legitimate according to object lifetime and pointer arithmetic rules in C++11*, but It Works In Practice.

*) in the same way that std::vector cannot be implemented in C++11

Upvotes: 5

Related Questions