C ++ - Which one should use the "new car" or "new car ()"?

Possible duplicate:
Are parentheses made after the type name with a new one?

Hello to all,

class Car { public: Car() : m_iPrice(0) {} Car(int iPrice) : m_iPrice(iPrice) {} private: int m_iPrice; }; int _tmain(int argc, _TCHAR* argv[]) { Car car1; // Line 1 Car car2(); // Line 2, this statement declares a function instead. Car* pCar = new Car; // Line 3 Car* pCar2 = new Car(); // Line 4 return 0; } 

Here is my question:

When we define a Car object, we should use Line 1, not Line 2. When we are a new object, both Line 3 and Line 4 can pass the VC8.0 compiler. However, what is the best way to Line 3 or Line 4? Line 3 is equal to line 4.

thanks

+4
source share
3 answers

In this case, the lines are equivalent; there is no difference in work.

However, be careful - this does not mean that such lines are ALWAYS equivalent. If your data type is a POD (i.e. a simple structure:

 struct Foo { int a; float b; }; 

Then new Foo creates an uninitialized object, and new Foo() calls the value initialization constructor, the value of which initializes all fields, i.e. sets in this case the value 0.

Since in such cases it is easy to accidentally call new Foo() , forget to initialize the objects (this is great!), And then accidentally make your own non-POD class (in this case, the value will not be initialized and the object will be uninitialized again), a little better always invoke new Foo (although this causes a warning in some versions of MSVC).

+6
source

It does not matter when the type new has a declared constructor.

If this is not the case, line 4 initializes all members to zero first (but only call constructors for those members that have declared constructors) and does the same with the base classes. If you do not want to do this, use line 3. This rule also holds for complex objects with virtual member functions, base classes, etc. - only the condition is whether the class has a declared user constructor.

This is a very subtle C ++ corner, and I think that I will not base my code on these facts without having a comment explaining what is in the code (oh, dear, my colleagues will be angry with me differently).

+2
source

Source: https://habr.com/ru/post/1333807/


All Articles