我试图将参数传递给构造函数,但同时制作一个像这样的对象数组。我使用以下代码到达那里:
PointPtr centroids = new Point[k](5);
好吧,这不是语法错误,但它没有编译。我真的不想将“5”硬编码为Point的默认构造函数。对我应该怎么做有什么想法?谢谢!
顺便说一句,我做到了 typedef Point *PointPtr
其他地方已经。
对不起,如果标题不准确。我不知道如何总结这一点。
我试图将参数传递给构造函数,但同时制作一个像这样的对象数组。我使用以下代码到达那里:
PointPtr centroids = new Point[k](5);
好吧,这不是语法错误,但它没有编译。我真的不想将“5”硬编码为Point的默认构造函数。对我应该怎么做有什么想法?谢谢!
顺便说一句,我做到了 typedef Point *PointPtr
其他地方已经。
对不起,如果标题不准确。我不知道如何总结这一点。
你可以创建一个指针数组(即 Point**
)并分两步初始化它们:
创建数组:
PointPtr* centroids = new PointPtr[k];
初始化:
for (int i=0 ; i<k ; ++i)
centroids[i]=new Point(5);
我建议用一个 std::vector
:
std::vector<Point> v(k, Point{5});
但你也可以这样做:
Point* centroids = new Point[5]{{1}, {2}, {3}, {4}, {5}};
如果你不能使用 std::vector
,然后一个选项是动态分配一个指针数组,然后动态分配n个对象,并将结果内存分配给数组中的指针。例如:
constexpr auto ARRAYSIZE = 5;
auto x = new PointPtr[ARRAYSIZE]; // should check for memory alloc errors
for (int i = 0; i < ARRAYSIZE; ++i)
{
x[i] = new Point(5); // pass any arguments you want, remember to check if allocation was successful
}
请注意,这种做法不赞成因为你真的不应该使用 new
除非你有充分的理由这样做(而IMO是愚蠢的,你不允许以正确的方式做事并从一开始就教好的做法);改为使用 std::vector
和智能指针,他们应该能够满足你所有的动态内存需求。
注1:使用标准库(即
std::vector
在这种情况下)处理事情是优惠的!注意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);
或者你可以手动处理它
// 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));
我至少将内存处理包装到函数(如果不是类)中:
#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);
}
并使用它们
auto p = new_n<Point>(k, 5);
// stuff using k Points in p constructed by passing 5 to constructors
remove_n(p, k);