c++ - 从引用复制构建

标签 c++ constructor reference copy-constructor

考虑这段代码

class Foo {
private:
    Bar bar; //note: no reference

public:
   Foo(Bar& b) : bar(b) { }
};

Bar 会被复制构造吗?

最佳答案

这取决于 Bar 的公共(public)构造函数的签名(显式或隐式定义)。

首先,C++ 标准允许引用的隐式转换,只要基础类型的唯一区别是目标类型至少与源类型一样cv 限定,使用此表中定义的部分排序(C++11,§3.9.3/4):

no cv-qualifier < const
no cv-qualifier < volatile
no cv-qualifier < const volatile
const          < const volatile
volatile    < const volatile

因此,考虑到这一点以及§12.8/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.

如果 Bar 有一个带有以下任何签名的构造函数:

Bar(Bar&);
Bar(Bar const&);
Bar(Bar volatile&);
Bar(Bar const volatile&);

那么是的,b 将被复制构造为 Foo::bar


编辑: 这是不正确的,我正在考虑 operator= 以及移动赋值运算符资格的详细信息。 p>

请注意,可以有一个不是复制构造函数的合格构造函数:

Bar(Bar);

这可以工作(读:编译),但从技术上讲它不是一个复制构造函数。

关于c++ - 从引用复制构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8143711/

相关文章:

c# - 递归拉取所有构造函数选项?

c++ - 运算符+ 重载错误。无法返回对对象的引用

c++ - libicuuc.so.52,需要 libboost_regex-mt.so

C++友元继承

javascript - 返回类构造函数的函数的类型声明

c# - Initialize() vs Constructor() 方法,正确使用对象创建

c++ - 为什么 “using namespace std;”被视为不良做法?

c++ - 如何将视频数据馈送到 DirectShow 过滤器以压缩/编码并保存到文件?

c++ - 返回 STL 容器元素的引用

compact-framework - 紧凑框架中是否有很多好的 list ?