初始化静态对象数组c ++

问题描述 投票:-1回答:1

如何为以下类声明“数据库”对象数组(无动态内存)?

class DataBase
{
 public: 
      DataBase(int code);
 private:
      Database();
      Database(const Database &);
      Database &operator=(const Database &);
 };
c++ static initialization
1个回答
4
投票

在C ++ 17及更高版本中,或者像这样:

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

或者使用显式构造函数:

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

预C ++ 17,您可以尝试这样的事情:

#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);

现在你可以使用db_ptr[0]等。根据C ++ 11 *中的对象生存期和指针算术规则,这并不完全合法,但它在实践中有效。

*)与在C ++ 11中无法实现std :: vector的方式相同

© www.soinside.com 2019 - 2024. All rights reserved.