C ++中构造函数的返回类型 [英] return type of the constructor in C++
问题描述
我知道C ++中没有返回类型的构造函数
I know that there is no return type of the constructors in C++
但是,下面的代码编译正确。下面的代码中构造函数返回的是什么?
However, the code below compiles right. What is returned by the constructor in the code below?
class A{
public:
A() {}
}
A a = A(); //what is returned by A() here, why?
这里是否有冲突?
推荐答案
构造函数不返回任何内容。语法 A()
不是构造函数调用,它创建一个 A
类型的临时对象(并调用构造函数
Nothing is returned from the constructor. The syntax A()
is not a constructor call, it creates a temporary object of type A
(and calls the constructor in the process).
您不能直接调用构造函数,构造函数将作为对象构造的一部分进行调用。
You can't call a constructor directly, constructors are called as a part of object construction.
在代码中,在临时构造过程中,将调用默认构造函数(您定义的构造函数)。然后,在 a
的构造过程中,使用临时变量作为参数来调用复制构造函数(由编译器自动生成)。
In your code, during the construction of the temporary the default constructor (the one you defined) is called. Then, during the construction of a
, the copy constructor (generated automatically by the compiler) is called with the temporary as an argument.
正如Greg正确指出的,在某些情况下(包括这一个),允许编译器避免复制构造和默认构造 a
复制构造函数必须可访问)。我知道没有编译器不会执行这样的优化。
As Greg correctly points out, in some circumstances (including this one), the compiler is allowed to avoid the copy-construction and default-construct a
(the copy-constructor must be accessible however). I know of no compiler that wouldn't perform such optimization.
这篇关于C ++中构造函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!