构造函数调用机制 [英] constructor invocation mechanism

查看:124
本文介绍了构造函数调用机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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)默认
2)复制

实际输出:






我对构造函数调用机制的理解有什么问题?



注意为了简洁,我省略了头文件。

解决方案

案例1)



m 被解释为函数return my ,并且不带参数。
查看预期输出remove ()即使用 my m;



情况2)



这是一个更好地称为最讨厌的解析的东西。


$ b b

n 被解释为返回 my 的函数,它接受函数返回的类型指针的参数<$

在这种情况下查看预期的输出try my n( c $ c>]



我的解释:



my n((my()))等效于 my n = my()。现在,右值表达式 my()创建了一个临时的(即调用默认构造函数)和 n 到该临时对象[由于某些编译器优化]



PS :我不能100%确定我的答案的最后一部分。如果我错了,请更正我。


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.

解决方案

Case 1)

m is interpreted as a function return my and taking no arguments. To see the expected output remove () i.e use my m;

Case 2)

This is something better known as the "Most vexing parse".

n is interpreted as a function returning my that takes an argument of type pointer to function returning my 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 to my n = my(). Now the rvalue expression my() creates a temporary[i.e a call to the default constructor] and n 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.

这篇关于构造函数调用机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆