0

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 &);
 };
3
  • Please add what you have already tried to solve your problem to your question so that ppl can more easily help you. It is also always worth checking out the help center of stackoverflow: stackoverflow.com/help/how-to-ask. Commented Mar 5, 2018 at 15:51
  • 1
    The code will not compile unless we also fix the typos in the excerpt provided. Commented Mar 5, 2018 at 15:52
  • Arda - I've edited the code to add the semicolon at the end of the class Commented Mar 5, 2018 at 15:59

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

5 Comments

Kerrek SB: Thanks for your response, but the copy constructor is private. (So that solution didn't work)
@happyloman: As of C++17, there is no more copy. If you need a pre-C++17 answer, please say so (in which case it's not so easy).
@happyloman: Uninitialized storage and placement-new could be used pre-C++17.
Thank you. Yes, this is for C++11. Sorry, I wasn't aware.
Thank you, you're right, pre-C++11 is a lot of work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.