C++ 初始化对象的静态数组c++;

C++ 初始化对象的静态数组c++;,c++,static,initialization,C++,Static,Initialization,如何为下面的类声明“数据库”对象数组(无动态内存) class DataBase { public: DataBase(int code); private: Database(); Database(const Database &); Database &operator=(const Database &); }; 在C++17及更高版本中,如下所示: Database a[] = { 1, 2, 3 };

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

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

在C++17及更高版本中,如下所示:

Database a[] = { 1, 2, 3 };
#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);
或者使用显式构造函数:

Database a[] = { Database(1), Database(2), Database(3) };
在C++17之前,您可以尝试以下方法:

Database a[] = { 1, 2, 3 };
#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);
#包括
std::对齐的_存储::类型db_存储;
数据库*db_ptr=重新解释强制转换(&db_存储);
新(db_ptr+0)数据库(1);
新(db_ptr+1)数据库(2);
新(db_ptr+2)数据库(3);
现在您可以使用
db_ptr[0]
等。根据C++11*中的对象生存期和指针算术规则,这并不是完全合法的,但它在实践中是有效的


*)同样,std::vector不能在C++11和C++17及更高版本中实现,如下所示:

Database a[] = { 1, 2, 3 };
#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);
或者使用显式构造函数:

Database a[] = { Database(1), Database(2), Database(3) };
在C++17之前,您可以尝试以下方法:

Database a[] = { 1, 2, 3 };
#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);
#包括
std::对齐的_存储::类型db_存储;
数据库*db_ptr=重新解释强制转换(&db_存储);
新(db_ptr+0)数据库(1);
新(db_ptr+1)数据库(2);
新(db_ptr+2)数据库(3);
现在您可以使用
db_ptr[0]
等。根据C++11*中的对象生存期和指针算术规则,这并不是完全合法的,但它在实践中是有效的


*)正如std::vector不能在C++11中实现一样,Kerrek SB:谢谢你的回答,但是复制构造函数是私有的。(所以那个解决方案不起作用)@happyloman:从C++17开始,就没有拷贝了。如果你需要一个C++17之前版本的答案,请说出来(在这种情况下就不那么容易了)。@happyloman:未初始化的存储和新位置可以在C++17之前使用。谢谢。是的,这是针对C++11的。对不起,我不知道。谢谢,你说得对,C++11之前的版本需要做很多工作!Kerrek SB:谢谢你的回复,但是复制构造函数是私有的。(所以那个解决方案不起作用)@happyloman:从C++17开始,就没有拷贝了。如果你需要一个C++17之前版本的答案,请说出来(在这种情况下就不那么容易了)。@happyloman:未初始化的存储和新位置可以在C++17之前使用。谢谢。是的,这是针对C++11的。对不起,我不知道。谢谢,你说得对,C++11之前的版本需要做很多工作!请将您已经尝试解决的问题添加到您的问题中,以便ppl可以更轻松地帮助您。同样值得查看stackoverflow的帮助中心:。除非我们还修复了提供的摘录中的打字错误,否则代码将无法编译。Arda-我编辑了代码,在类的末尾添加了分号。请将您已经尝试解决的问题添加到您的问题中,以便ppl可以更轻松地帮助您。同样值得查看stackoverflow的帮助中心:。除非我们还修复了提供的摘录中的打字错误,否则代码不会编译。Arda-我已经编辑了代码,在类的末尾添加了分号