构造函数调用机制
struct my
{
my(){ std::cout<<"Default";}
my(const my& m){ std::cout<<"Copy";}
~my(){ std::cout<<"Destructor";}
};
int main()
{
my m(); //1
my n(my()); //2
}
预期输出:
1 ) Default
2 ) Copy
实际输出:
我对构造函数调用机制的理解有什么问题?
注意
为了简洁起见,我省略了头文件。
struct my
{
my(){ std::cout<<"Default";}
my(const my& m){ std::cout<<"Copy";}
~my(){ std::cout<<"Destructor";}
};
int main()
{
my m(); //1
my n(my()); //2
}
Expected output :
1 ) Default
2 ) Copy
Actual output :
What's wrong with my understanding of the constructor invoking mechanism?
Note
I have omitted header files for brevity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
情况 1)
m
被解释为函数返回my
并且不带任何参数。要查看预期的输出,请删除
()
,即使用my m;
情况 2)
这是更广为人知的“最令人烦恼的解析”。
n
被解释为返回my
的函数,该函数接受一个指针类型的参数,该函数返回不带任何参数的my
函数。要查看这种情况下的预期输出,请尝试
my n((my()));
[编译器不再像前一种情况那样将其视为参数规范,而是将其解释为表达式,因为额外的()
]我的解释:
my n((my()))
相当于my n = my()
。现在,右值表达式my()
创建一个临时对象[即对默认构造函数的调用],并且n
被复制初始化为该临时对象[不调用复制向量由于一些编译器优化]PS :我对我的答案的最后部分不是100%确定。如果我错了请纠正我。
Case 1)
m
is interpreted as a function returnmy
and taking no arguments.To see the expected output remove
()
i.e usemy m;
Case 2)
This is something better known as the "Most vexing parse".
n
is interpreted as a function returningmy
that takes an argument of type pointer to function returningmy
taking no arguments.To see the expected output in this case try
my n((my()));
[Instead of treating as an argument specification as in the former case the compiler would now interpret it as an expression because of the extra()
]My interpretation:
my n((my()))
is equivalent tomy n = my()
. Now the rvalue expressionmy()
creates a temporary[i.e a call to the default constructor] andn
is copy initialized to that temporary object[no call to the copy-ctor because of some compiler optimization]P.S: I am not 100% sure about the last part of my answer. Correct me if I am wrong.
与 Prasoon 一样,我怀疑 C++ 编译器正在以您意想不到的方式解析您的代码。例如,我认为它将该行解析
为函数原型声明,而不是变量声明并调用构造函数 - 这就是为什么你看不到输出。
Like Prasoon, I suspect the C++ compiler is parsing your code in a way you don't expect. For example, I think it is parsing the line
as a function prototype declaration, not as a variable declaration and call to the constructor - hence why you see no output.