c++ - 使用参数构造函数模拟 new[]

标签 c++ arrays constructor new-operator

如果我没有修改参数构造函数中的任何 static 变量,则低于模拟 new T[N] (x,y); (数组新的参数)?

template<typename T>
void* operator new [] (size_t size, const T &value)
{
  T* p = (T*) malloc(size);
  for(int i = size / sizeof(T) - 1; i >= 0; i--)
    memcpy(p + i, &value, sizeof(T));
  return p;
}

用法将是,

struct A
{
  A () {}  // default
  A (int i, int j) {} // with arguments
};

int main ()
{
  A *p = new(A(1,2)) A[10];  // instead of new A[10](1,2)
}

最佳答案

我建议

 std::vector<A> v(10, A(1,2));

我意识到这并没有真正解决数组的问题。 你可以使用

 p = &v[0]; 

因为标准保证连续存储。不过,调整 vector 大小时要非常小心,因为它可能会使 p 无效

我检查了 boost::array<>(适应 C 风格的数组),但它没有定义构造函数...

关于c++ - 使用参数构造函数模拟 new[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6070231/

相关文章:

java - Java数组中的for循环不准确

javascript - TypeScript 中带有配置对象的构造函数(如 jQuery.extend、Ext.apply)

c++ - 在返回 shared_ptr 的函数中返回新的东西

c++ - 是否可以将 nginx 嵌入到 C/C++ 应用程序中

c - 将函数返回赋值给 char 数组变量

c++ - 比较两个指针以用于标准算法的正确方法

c - 在C中,是否保证数组起始地址小于其他元素的地址?

perl - 我可以在构造函数中使用访问器方法吗?

c++ - 如何以可移植的方式自动检测 C++ 中的内存泄漏?

c++ - 如何在 linux 中使用 cpp 读取 .xls 文件