当我们创建类类型的动态数组时,我正在研究这种情况。据我所知,没有一种方法可以在直接调用类的非默认构造函数时创建数组。一种方法是正常初始化数组,然后循环并调用每个对象的非默认构造函数,但我认为这种方法有很大的开销。在寻找解决方案后,我发现使用新的放置方式如下:
void* memory = operator new[](sizeof(Test) * 8); // Allocate raw memory for 8 objects
Test* arr = static_cast<Test*>(memory); //Convert to desired type
// Construct objects using placement new
for (int i = 0; i < 8; i++) {
new (&arr[i]) Test(9); //Assume Test has constructor Test(int)
}
// Use the initialized array
for (int i = 0; i < 8; i++) {
arr[i].~test(); // Explicitly call destructor for each object
}
operator delete[](memory); // Deallocate memory
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以按以下方式释放内存:
delete[] arr; …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我尝试使用 emplace_back 进行聚合初始化。这里的问题是 emplace_back 接受构造函数参数并直接在向量中构造对象,我想知道是否在 a 上调用了复制构造函数A{1,2,3}。但是,为了使聚合初始化起作用,该结构不应具有用户定义的构造函数。你知道幕后发生了什么吗?
#include <iostream>
#include <vector>
struct A {
int x, y, z;
/*A(int x, int y, int z) : x(x), y(y), z(z)
{
std::cout << "ctor called\n";
}
A(const A& other) : x(other.x), y(other.y), z(other.z) {
std::cout << "copy ctor called\n";
}*/
};
int main() {
std::vector<A> vec;
vec.emplace_back(A{1, 2, 3});
return 0;
}
Run Code Online (Sandbox Code Playgroud)