- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
假设我对以下两种创建调用默认构造函数(由编译器提供)的对象的方法的了解都是正确的。
class A
{
int a,b;
//No programmer defined constructor
}
...
A o1; //Implicit Call I believe
A o2 = A(); //Explicit Call
为什么 A o2 = A();
导致对象 o2
的成员 (a,b) 使用默认值 (0) 而不是 初始化自身>A o;
(它们是用垃圾值初始化的)?它是未定义的行为吗?
最佳答案
引自标准 p8.5/1
这里没有用户定义的构造函数,因此,编译器将使用默认构造函数。并且默认构造函数不会用零初始化成员。
If no initializer is specified for an object, the object isdefault-initialized.
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type (Clause 9), constructorsare considered. The applicable constructors are enumerated (13.3.1.3),and the best one for the initializer () is chosen through overloadresolution (13.3). The constructor thus selected is called, with anempty argument list, to initialize the object.
第二种情况是值初始化。
An object whose initializer is an empty set of parentheses, i.e., (),shall be value-initialized.
To value-initialize an object of type T means:
if T is a (possibly cv-qualified) class type without a user-providedor deleted default constructor, then the object is zero-initializedand the semantic constraints for default-initialization are checked,and if T has a non-trivial default constructor, the object isdefault-initialized;
To zero-initialize an object or reference of type T means:
if T is a (possibly cv-qualified) non-union class type, eachnon-static data member and each base-class subobject iszero-initialized and padding is initialized to zero bits;
关于c++ - 隐式与显式默认构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32377780/
我是一名优秀的程序员,十分优秀!