c++ - Foo(Foo x){ } 会在 C++ 中被调用吗?

标签 c++

我有一个关于 C++ 语法/构造的查询:在什么情况下可以调用以下 Foo(Foo x){}? 我知道它不会像初始化一样被调用,因为它们会调用复制构造函数

Foo a;
Foo x = a;
or 
Foo x(a);

不用于类型转换,因为传递给它的参数与类的类型相同

想不出调用 Foo(Foo x){} 的场景,否则它永远是死代码。

class Foo { 
  public :
    Foo(Foo x){  // notice it is not not a Copy constructor!!, i intented it to make like ordinary ctor taking same class object
    }
    Foo(int x) : m_data(x){}
private :
  int m_data;
};

最佳答案

你真的试过编译这段代码吗?

Error   1   error C2652: 'Foo' : illegal copy constructor: first parameter must not be a 'Foo'  main.cpp    5   1   NativeConsoleSketchbook

C++11 标准,12.8.6:

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments.

关于c++ - Foo(Foo x){ } 会在 C++ 中被调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780420/

相关文章:

c++ - 返回具有特定变量的对象

c++ - AMQP-CPP - RabbitMQ 事件循环不工作

c++ - gdb如何在dlopen打开的动态库中设置断点

c++ - 快速傅里叶变换

c++ - 将多边形从 3d 空间展开到 2d 空间(使用三角形)以获得纹理坐标

c++ - 如何转发声明已在其他地方使用默认值转发声明的模板类型

c++ - 我的好友模板可以在其实例化中提及我的私有(private)成员吗?

c++ - 为什么这个过滤器不起作用?

c++ - 按值|引用调用的另一个问题

c++ - 如何关闭程序中用于打印调试数据的功能