如果我没有定义自己的构造函数,Base *b = new Base;和Base *b = new Base();有什么区别吗?
发布于 2010-09-13 16:17:59
初始化是标准中要遵循的一种PITA…然而,这两个已经存在的答案在他们错过的地方是不正确的,这使得他们断言没有区别。
在没有用户定义构造函数的类中调用new T和new T()之间有很大的不同。在第一种情况下,对象将是默认初始化的,而在第二种情况下,它将是``value initialized*。如果对象包含任何POD子对象,则第一个将保持POD子对象未初始化,而第二个将每个子元素设置为0。
struct test {
int x;
std::string s;
};
int main() {
std::auto_ptr<test> a( new test );
assert( a->s.empty() ); // ok, s is string, has default constructor
// default constructor sets it to empty
// assert( a->x == 0 ); // this cannot be asserted, the value of a->x is
// undefined
std::auto_ptr<test> b( new test() );
assert( b->s.empty() ); // again, the string constructor sets to empty
assert( b->x == 0 ); // this is guaranteed by *value-initialization*
}漫漫长路。默认-对于用户定义的类,初始化意味着调用默认构造函数。在没有用户提供默认构造函数的情况下,它将调用隐式定义的默认构造函数,该构造函数相当于具有空初始化列表和空体(test::test() {})的构造函数,这反过来将导致每个非POD子对象的默认初始化,并使所有POD子对象未初始化。由于std::string有一个用户(根据用户的某种定义,包括标准库编写器)提供的构造函数,它将调用这样的构造函数,但不会在x成员上执行任何真正的初始化。
也就是说,对于具有用户提供的默认构造函数的类,new T和new T()是相同的。对于没有这样的构造函数的类,它取决于类的内容。
发布于 2010-09-13 11:51:00
编辑:查看@David的答案--这是错误的,但我不能删除它,因为它是被接受的
这两种情况都没有区别--您是否定义自己的构造函数并不重要。
唯一的区别是,对于原语类型(即int或float),添加()会将值初始化为零。(Demonstration on Codepad)
参见此示例(输出在codepad上)
#include <iostream>
struct ConstructorChecker
{
ConstructorChecker()
{
std::cout << "Hey look! A new constructor checker!" << std::endl;
}
};
struct BasicClass
{
};
int main()
{
//Note constructor called in both cases.
ConstructorChecker *one = new ConstructorChecker;
delete one;
ConstructorChecker *two = new ConstructorChecker();
delete two;
//Same deal -- just because the compiler provides the constructor doesn't mean
//it behaves any differently.
BasicClass *basic = new BasicClass;
delete basic;
BasicClass *basic2 = new BasicClass();
delete basic2;
return 0;
}发布于 2010-09-13 12:19:24
正如比利提到的,两者都是一样的。
这被称为“值初始化语法”($8.5/7)。
初始值设定项是一组空括号的对象,即(),应该是值初始化的。
https://stackoverflow.com/questions/3697750
复制相似问题