无对复制构造函数的调用 [英] No call to the copy constructor

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

问题描述

请考虑这一点:

#include <iostream>

struct A{
   A(){
       std::cout << "Create empty A" << std::endl;
   }

   A(const A& a){
       // Why is this never called??
       std::cout << "Never called" << std::endl;
   }
};

A genA() {
   A a;
   return a;
}

int main(int argc, const char *argv[])
{
   A a(genA()); // Expected to call copy constructor
   return 0;
}

为什么不调用复制构造函数?

Why is the copy constructor not called?

如果我想确保每次复制A时屏幕上都会显示从不调用,我该怎么办。

What should I do if I want to ensure that "Never called" is printed on the screen every time I copy A.

推荐答案

这被称为 返回值优化

编译器可以优化您的代码,以便它直接在将要被复制的位置创建对象。因此,没有理由使用复制构造函数。

This is called as Return value optimization.
Compiler can optimize your code so that it bulds the object directly in the location where it would have been copied too. Thus there will be no reason to use the copy constructor.

注意:标准明确允许这样做。

Note: The standard explicitly allows it do so.

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

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