在 C++ 中,"new/delete" 在结构上代替 "malloc/free" 有多好?
How good is "new/delete" on struct in place of "malloc/free", in C++?
很多次,我在 C++ 代码中看到结构的指针分配;
struct Current{
int amp;
};
Current *cur = new Current();
然而,"Current" 是一个结构,而不是这里的 class,但在 C++ 中受支持。用这个代替C型分配有多好,如下:
Current *cur = (Current*) malloc (sizeof(Current));
这背后的基本概念是什么?我知道的一个是,"structs" 在 C++ 中被视为 "classes"。
C++ 中 struct-VS-class 的概念是已知的。查询主要是关于特定的用例,因为两者都是允许的,但应该优先于哪个,为什么?
在 C++ 中,struct
与 class
相同,只是它具有默认的 public
成员以及默认的 public
继承。
至于malloc
的使用,虽然可以使用,但是正如你所说的C
类型的分配,不应该用于C++
.如果必须,您可以像 class.
一样对结构使用 malloc/free
但是,正确的 C++
方法是使用 new
和 delete
,它们在 struct
和 [=12= 中的用法相同].
如果您对 为什么应该使用 new/delete
而不是 malloc/free
感到好奇,我建议您参考这个 Q/A: In what cases do I use malloc vs new?
就括号的使用而言,即:
Current *cur = new Current();
//vs.
Current *cur = new Current;
看到这个:Do the parentheses after the type name make a difference with new?
我自己做了,学到了新东西。
你误解了struct
s。
However, "Current" is a structure and not class here, but is supported in C++
错了。 Current
是一个class。如果您使用关键字 class
而不是关键字 struct
.
声明它,它也将是 class
提供关键字 struct
是为了向后兼容,使用它会更改定义语法中的一些可见性默认值。但是,否则,您仍然只是在定义 class.
当然,用 struct
定义的 classes 没有什么神奇之处,这意味着您应该回到古老的 C 风格分配。
很多次,我在 C++ 代码中看到结构的指针分配;
struct Current{
int amp;
};
Current *cur = new Current();
然而,"Current" 是一个结构,而不是这里的 class,但在 C++ 中受支持。用这个代替C型分配有多好,如下:
Current *cur = (Current*) malloc (sizeof(Current));
这背后的基本概念是什么?我知道的一个是,"structs" 在 C++ 中被视为 "classes"。
C++ 中 struct-VS-class 的概念是已知的。查询主要是关于特定的用例,因为两者都是允许的,但应该优先于哪个,为什么?
在 C++ 中,struct
与 class
相同,只是它具有默认的 public
成员以及默认的 public
继承。
至于malloc
的使用,虽然可以使用,但是正如你所说的C
类型的分配,不应该用于C++
.如果必须,您可以像 class.
malloc/free
但是,正确的 C++
方法是使用 new
和 delete
,它们在 struct
和 [=12= 中的用法相同].
如果您对 为什么应该使用 new/delete
而不是 malloc/free
感到好奇,我建议您参考这个 Q/A: In what cases do I use malloc vs new?
就括号的使用而言,即:
Current *cur = new Current();
//vs.
Current *cur = new Current;
看到这个:Do the parentheses after the type name make a difference with new?
我自己做了,学到了新东西。
你误解了struct
s。
However, "Current" is a structure and not class here, but is supported in C++
错了。 Current
是一个class。如果您使用关键字 class
而不是关键字 struct
.
提供关键字 struct
是为了向后兼容,使用它会更改定义语法中的一些可见性默认值。但是,否则,您仍然只是在定义 class.
当然,用 struct
定义的 classes 没有什么神奇之处,这意味着您应该回到古老的 C 风格分配。