C ++中的new和malloc之间的区别 [英] differences between new and malloc in c++
问题描述
#include <iostream>
#include <cstdlib>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
void printer(int x)
{
cout<<x<<" printer"<<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( ) {
Box* myBoxArray = new Box[4];
Box* myBoxArray2 = (Box*)malloc(sizeof(Box[4]));
myBoxArray2->printer(23);
*myBoxArray2;
*(myBoxArray2).printer(23);
return 0;
}
问题很简单,当我使用'new'时,构造函数被打印出来,但是当我简单地反引用myBoxArray2
的指针时,构造函数不会被打印,功能printer
也不会被打印.
也是为什么当我使用->
时功能打印机运行,但是当我使用等效的*(myBoxArray2).printer(23)
the problem simply is that when i use 'new' the constructor is printed out but when i simple derefrence the pointer to myBoxArray2
the constructor is not printed and neither is the funtion printer
printed.
Also why is it that when i use ->
the funnction printer runs but not when i use the equivalent *(myBoxArray2).printer(23)
推荐答案
malloc
仅分配内存 ,它不会调用会使对象保持不确定状态的构造函数.
malloc
allocates memory only, it doesn't invoke constructors which can leave objects in an indeterminate state.
在C ++中,您几乎切勿使用malloc
,calloc
或free
.并且尽可能避免使用new
和new[]
,而是使用对象实例或实例向量.
In C++ you should almost never use malloc
, calloc
or free
. And if possible avoid new
and new[]
as well, use object instances or vectors of instances instead.
对于第二个问题(与第一个问题确实无关),由于.
选择运算符具有较高的
As for your second question (which is really unrelated to the first), *(myBoxArray2).printer(23)
is wrong since the the .
selection operator have higher precedence than the dereference operator *
. That means first of all that you use the .
member selector on a pointer which is invalid, and that you attempt to dereference what printer
returns which is also wrong since it doesn't return anything.
您要(*myBoxArray2).printer(23)
(请注意,星号的位置在括号内的 内),它与myBoxArray2->printer(23)
完全相同..
You want (*myBoxArray2).printer(23)
(note the location of the asterisk is inside the parentheses), which is exactly the same as myBoxArray2->printer(23)
.
还请注意,myBoxArray2->printer(23)
与myBoxArray2[0].printer(23)
相同.
这篇关于C ++中的new和malloc之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!