Search code examples
c++copy-constructorprivate-constructordefault-copy-constructor

Advice on Copy Constructor of a Class containing a non-copyable member reference


I have a class A which has an reference to an object of class B as a member. The copy constructor (and assignment operator) of class B is private. Do you think it is a valid and good idea to use the default copy constructor for A. (I actually want a functionality where I can store a lots of object for type A in some sort of an STL Container which requires both assign-ability and copy-ability.)

class A
{
    private:
        B& b_;

    public:
        A(B& b) : b_(b){}
}

Till now, in my knowledge the objections to above method are the following but my design does not face it. I would like to know if there are some other problems/issues/concerns about the above example...

  1. Only the reference is copied and hence, there would be problems when the original object b of type B is destroyed. (Does not apply, because b is available throughout the entire scope.)
  2. Is b_ unique for every instance of A? (No, B is actually instantiated only once in the scope, so it has the effect of a singleton class.)

If there are other concerns, please list them here. I am not keen on a explicitly defined copy-constructor but i'm keeping an open mind towards it.


Solution

  • As a general guideline, I never store references inside objects because I cannot get copy semantics for free.

    I store pointers instead. Here, storing a dumb pointer and letting the compiler implement copy semantics for you seems fine:

    class A
    {
        B* b; // or a smart pointer, depending on what semantics you want.
    
    public:
        A(B& b) : b(&b) {}
    };
    

    Using a pointer has some flexibility: for instance, default construction can set the pointer to zero, and subsequent operations check against its validity (or simply assert). Also, the pointer can be reset, which is not the case with a reference.