What's the difference between new and parentheses?

Asked 1 years ago, Updated 1 years ago, 87 views

When you create an instance of the Test class that I define.

What's the difference between the two? Is there a difference?

c++ constructor initialization new-operator

2022-09-21 18:55

1 Answers

There's a difference between the two. It can affect the code.

The memory that new has return is Depending on whether the object you are creating now is POD or if you have a POD member that writes the default generator (compiler) Sometimes it may be initialized, sometimes it may not be initialized.

In C++1998, two initialization methods: 0 and default In C++2003, three initialization methods: 0, default, value

Assuming the following situations exist

struct A { int m; }; // POD(o)
struct B { ~B(); int m; }; // POD(x). Write the default constructor created by the compiler
struct C { C() : m() {}; ~C(); int m; }; // POD(x). Default initial value of m is set

In the C++98 compiler, new is written as follows:

In the C++03 compiler:

To summarize, Since A is POD, new A and new A() are different in all versions new B() has different results depending on the compiler.

In conclusion, it's better to put parentheses Sometimes there's a difference, but sometimes there's no difference Sometimes it doesn't matter.


2022-09-21 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.