从参考复制构建
考虑这段代码
class Foo {
private:
Bar bar; //note: no reference
public:
Foo(Bar& b) : bar(b) { }
};
Bar 会被复制构造吗?
Consider this code
class Foo {
private:
Bar bar; //note: no reference
public:
Foo(Bar& b) : bar(b) { }
};
Will Bar get copy-constructed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于
Bar
的公共构造函数的签名(显式或隐式定义)。首先,C++ 标准允许引用的隐式转换,只要基础类型的唯一区别是目标类型至少与源类型一样cv 限定,使用部分此表中定义的顺序(C++11,§3.9.3/4):
因此,考虑到这一点以及§12.8/2:
如果 Bar 的构造函数具有以下签名中的任何:
那么是的,
b
将被复制构造为Foo::bar
。编辑: 这是不正确的,我正在考虑
operator=
以及移动赋值运算符资格的详细信息。请注意可以有一个不是复制构造函数的合格构造函数:这可以工作(读取:编译),但从技术上讲它不是复制构造函数。That depends on the signatures of
Bar
's public constructors, either explicitly or implicitly defined.To start with, the C++ standard allows for implicit conversion of references as long as the only difference in the underlying type is that the destination type is at least as cv-qualified than the source type, using the partial ordering defined in this table (C++11, §3.9.3/4):
So, taking that into account as well as §12.8/2:
if Bar has a constructor with any of the following signatures:
then yes,
b
will be copy-constructed intoFoo::bar
.EDIT: This was incorrect, I was thinking of
operator=
and the details of qualifying as a move-assignment operator.Note that it's possible to have an eligible constructor that is not a copy constructor:This will work (read: compile), but it is not technically a copy constructor.是的,您的成员变量
bar
将被复制构造,这是使用初始值设定项列表的好处之一,而不是在构造函数主体中分配值。如果
Bar
类没有可访问的复制构造函数,并且编译器无法生成默认复制构造函数,则代码将无法编译。当您将引用传递给复制构造函数时,通常应该将其设为
const
引用。Yes your member variable
bar
will be copy constructed, that's one of the benefits of using an initializer list as opposed to assigning the value in the body of the constructor.If the
Bar
class does not have an accessible copy constructor and the compiler can't generate a default one, the code will fail to compile.When you pass a reference to a copy constructor, you should generally make it a
const
reference.