[英]initialize static array of objects c++
如何为以下类声明“数据库”对象的数组(无动态内存)?
class DataBase
{
public:
DataBase(int code);
private:
Database();
Database(const Database &);
Database &operator=(const Database &);
};
在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 *中的对象生存期和指针算术规则,这并不完全合法,但是在实践中db_ptr[0]
。
*)的方式与无法在C ++ 11中实现std :: vector的方式相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.