如何使用new传递构造函数参数

Jac*_*mas 11 c++

我试图将参数传递给构造函数,但同时创建一个像这样的对象数组.我使用以下代码到达那里:

PointPtr centroids = new Point[k](5);

好吧,这不是语法错误,但它没有编译.我真的不想将"5"硬编码为Point的默认构造函数.对我应该怎么做有什么想法?谢谢!

顺便说一句,我typedef Point *PointPtr已经在其他地方做过了.

对不起,如果标题不准确.我不知道如何总结这一点.

101*_*010 13

我建议使用std::vector:

std::vector<Point> v(k, Point{5});
Run Code Online (Sandbox Code Playgroud)

但你也可以这样做:

Point* centroids = new Point[5]{{1}, {2}, {3}, {4}, {5}};
Run Code Online (Sandbox Code Playgroud)

现场演示

  • 我不知道那样! (2认同)

Pix*_*ist 5

std::vector注1:最好使用标准库(即在本例中)来处理事情!

注2:就我个人而言,我不会走指针数组路线,因为你会破坏你的内存局部性。

您可以使用std::allocator

// Create allocator object
std::allocator<Point> alloc;
// allocate storage for k Points
Point * p = alloc.allocate(k);
// Construct k Points in p
for (std::size_t i{0}; i<k; ++i)
{
  alloc.construct(p+i, 5);
}
// Do stuff using p
// ...
// Destroy k objects in p
for (std::size_t i{0}; i<k; ++i)
{
  alloc.destroy(p+i);
}
// Dealloacte memory
alloc.deallocate(p, k);
Run Code Online (Sandbox Code Playgroud)

或者你可以手动处理

// allocate
Point * p = static_cast<Point*>(::operator new[](k*sizeof(Point)));
// placement new construction
for (std::size_t i{0}; i<k; ++i)
{
  new((void *)(p+i)) Point{5};
}
// stuff
// destruction
for (std::size_t i{0}; i<k; ++i)
{
  (p+i)->~Point();
}
// deallocation
::operator delete[](static_cast<void*>(p));
Run Code Online (Sandbox Code Playgroud)

我至少将内存处理包装到函数(如果不是类)中:

#include <new>
#include <utility>
#include <cstddef>

template<class T, class ... Args>
T * new_n(std::size_t const n, Args&&  ... args)
{
  T * p{ (T*)::operator new[](n*sizeof(T)) };
  for (std::size_t i{ 0 }; i < n; ++i) 
  {
    new((void*)(p + i)) T(std::forward<Args>(args)...);
  }
  return p;
}

template<class T>
void remove_n(T * const p, std::size_t const n)
{
  for (std::size_t i{ 0 }; i < n; ++i) (p + i)->~T();
  ::operator delete[]((void*)p);
}
Run Code Online (Sandbox Code Playgroud)

并使用它们

auto p = new_n<Point>(k, 5);
// stuff using k Points in p constructed by passing 5 to constructors
remove_n(p, k);
Run Code Online (Sandbox Code Playgroud)


Shl*_*oim -5

您可以创建一个指针数组(即Point**)并分两步初始化它们:

  1. 创建数组:

    PointPtr* centroids = new PointPtr[k];

  2. 初始化:

    for (int i=0 ; i<k ; ++i) centroids[i]=new Point(5);

  • 请注意,此解决方案为“centroids”提供了不同的类型;在原始版本中,它是一个“Point*”,在您的解决方案中它变成“Point**”。这确实应该在答案中更加明显。 (2认同)