A a(3)和A a=3有什么区别?
当A有单参数构造时,可以写成这两种形式。我想知道两种写法的实质是相同的吗?
[解决办法]
/* ISO/IEC 14882:2003(E)// from [dcl.init]Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the destination type. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.// from [class.temporary]When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1), it shall ensure that a constructor is called for the temporary object.// from [class.copy]A copy constructor for class X is trivial if it is implicitly declared and if— class X has no virtual functions (10.3) and no virtual base classes (10.1), and— each direct base class of X has a trivial copy constructor, and— for all the nonstatic data members of X that are of class type (or array thereof), each such class type has a trivial copy constructor;otherwise the copy constructor is non-trivial.*/
[解决办法]
两种形式是不一样的,他们最终的行为能够一样取决于临时变量能够被优化掉,而和拷贝构造函数是trivial还是non-trivial没有关系
To Vitin:
如果你的编译器决定优化掉临时变量,那么“When an implementation introduces a temporary object ”这个前提就不成立了
C++标准允许优化掉临时变量,但是要满足在优化前符合语法。
A a(3);--- direct-initialization直接寻找构造函数
A a=3; --- copy-initialization 因为3的类型和A的类型没有关联,这时候就不会直接寻找构造函数,而是先构造临时变量,然后使用构造起来的临时变量direct-initialize a
也就是说在临时变量不被优化的时候需要调用两个构造函数, 而这两个构造函数的调用都必须合乎语法,也就是说,如果A的拷贝构造函数不能被访问,那么编译器就应该报错;
class A
{
public:
A(int){}
private
A(const A&);
};
lz试试上面的声明就知道他们的区别了。
另外值得补充的是,
A a1;
A a2(a1)和A a2 = a1则是一样的