构造函数调用机制

发布于 2024-10-04 08:12:57 字数 369 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多彩岁月 2024-10-11 08:12:57

情况 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 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.

独﹏钓一江月 2024-10-11 08:12:57

与 Prasoon 一样,我怀疑 C++ 编译器正在以您意想不到的方式解析您的代码。例如,我认为它将该行解析

my m();

为函数原型声明,而不是变量声明并调用构造函数 - 这就是为什么你看不到输出。

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

my m();

as a function prototype declaration, not as a variable declaration and call to the constructor - hence why you see no output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文