开发者

C++ -- Which one is supposed to use "new Car" or "new Car()"? [duplicate]

开发者 https://www.devze.com 2023-02-01 15:42 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Do the parentheses after the type name make a difference with new?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Do the parentheses after the type name make a difference with new?

Hello 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 an object of Car, we should use Line 1 rather than Line 2. When we new an object, both Line 3 and Line 4 can pass the compiler of VC8.0. However, what is the better way Line 3 or Line 4? Or, Line 3 is equal to Line 4.

Thank you


In this case the lines are equivalent; there's no difference in operation.

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

struct Foo
{
    int a;
    float b;
};

Then new Foo produces a uninitialized object, and new Foo() calls a value initalization constructor, which value-initializes all fields - i.e. sets them to 0 in this case.

Since in such cases it's easy to accidentally call new Foo(), forget to initialize objects (this is fine!), and then accidentally make your class non-POD (in which case the value-initialization will not be done and the object will be uninitialized again), it's slightly better to always call new Foo (though this produces a warning in some MSVC versions).


It makes no difference when the type you new has a user declared constructor.

If it doesn't, then Line 4 will initialize all the members to zero first (but only call constructors for those members that have user declared constructors) and do the same to base classes. If you don't want to have that done, use Line 3. This rule also takes place for complex objects with virtual member functions, base classes and so on - only condition is whether or not the class has a user declared constructor.

This is a very subtle corner of C++, and I think I wouldn't base my code on these facts without having a comment explaining that in the code (oh dear, my colleagues will get mad at me otherwise).


This has been discussed earlier also C++ Classes default constructor and Is this' type variableofType()' function or object?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号