Copy-construct from reference

Consider this code

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

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

Will Bar get copy-constructed?


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):

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

So, taking that into account as well as §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.

if Bar has a constructor with any of the following signatures:

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

then yes, b will be copy-constructed into Foo::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.

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.

Need Your Help

Xamarin: changing JDK location in visual studio 2013

java visual-studio-2013 xamarin

It seems like you can't change the JDK location via Visual Studio.

Multi-threading best practices

multithreading synchronization

I have an application I've written in C#, although any similar language would apply here.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.