下面是一个简单的代码:
#include <iostream>
#include <string>
typedef struct Car{
std::string model;
} Car;
std::string get_model() {
std::string str = "Maserati";
return str;
}
int main() {
const int nCars = 2;
//Car *list = new Car[nCars]; // works everywhere g++/VC++
Car *list = (Car *)malloc(nCars * sizeof(Car)); // works in g++, not VC++
list[0].model = get_model();
std::cout << "model=" << list[0].model << std::endl;
// delete[] list;
free(list);
return 0;
}
有当我用的malloc()或新的以g ++没有问题。然而,的malloc()不会在Visual C ++工作。我应该使用新的时总是我分配在C ++类对象?
(A devtor)<> <
您无需调用构造函数或调用析构函数时,对象是即将被删除分配内存。这是new[]
和delete[]
为你做,所以使用它们 - 或者更好的是,使用智能指针 - 或者甚至更好,标准容器,比如std::vector
保持对象为您服务。
您与缺少的部分代码加入:
#include <iostream>
#include <string>
struct Car {
std::string model;
Car() { std::cout << "ctor\n"; }
~Car() { std::cout << "dtor\n"; }
};
int main() {
const int nCars = 2;
// allocate memory
Car *list = (Car *)malloc(nCars * sizeof(Car));
// manually calling constructors
for(int i=0; i<nCars; ++i) {
new(&list[i]) Car();
}
// use objects here
// manually calling destructors
for(int i=0; i<nCars; ++i) {
list[i].~Car();
}
// freeing memory
free(list);
}
使用new[]
和delete[]
比较:
int main() {
const int nCars = 2;
// create cars
Car* list = new Car[nCars];
// use objects here
// delete cars
delete[] list;
}
使用的容器比较:
int main() {
const int nCars = 2;
// create cars
std::vector<Car> list(nCars);
// use objects here
}
是。
虽然这是错误的说法,“不要在C ++中使用malloc()
,”这肯定是真的,你不应该使用malloc()
实例化一个类。
请记住,C ++,在某种意义上,它有效地支持C几乎完全的子集,并增加了的C ++功能的超集的混合语言。 malloc()
有一定的作用使用时播放内置的类型,如int
,char
,float
等。
对于对象,然而,new
必须使用。这可能是真的,你已经发现,malloc()
工作在许多情况下,但new
和delete
会造成构造函数和析构函数被调用,它绝不会与malloc()
和free()
发生。
这里的问题是,因为你分配你的车的struct的的std :: string内存,但不叫的std :: string构造函数。
你应该要求每个项目放置新的数组中调用构造函数并在汽车结构初始化的std :: string领域:
int main() {
const int nCars = 2;
Car* list = (Car *)malloc(nCars * sizeof(Car));
for (int i = 0; i < nCars; ++i)
new(&list[i])Car();
list[0].model = get_model();
std::cout << "model=" << list[0].model << std::endl;
}
- 原来的答案 -
下面是我原来的答复(这是不正确由于可能需要对数组的额外的开销:qazxsw POI)
如果你必须使用malloc的话,我建议你使用就地构造函数返回的内存块:
https://en.cppreference.com/w/cpp/language/new#Allocation