Copy constructor required to be explicity defined with mutex

231 views Asked by At

In my code, I have not defined copy constructors for Complex and Composition classes on purpose. I wish to use the copy constructor provided to me by the compiler

#include<boost/make_shared.hpp>
#include<boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

class Complex
{ 
  private : 
  std::string _a;
  std::string _b;
};

class Composition
{
  public:
    Composition(){}
    Composition(int x, int y)
    {
      _x = x;
      _y = y;
    }
  private:
    int _x;
    int _y;
    Complex obj;
};

int main()
{
  //Used make_shared this way on purpose
  boost::shared_ptr<Composition> ptr = boost::make_shared<Composition>(Composition(1,2) );
}

The code above compiles without any issues.

Now I change the complex class to follows

class Complex
{
  private : 
  std::string _a;
  std::string _b;
  boost::mutex _mutex;
};

When I compile the code, I get the error

/usr/local/include/boost/smart_ptr/make_shared.hpp:660: error: no matching function for call to ‘Composition::Composition(const Composition&)’
note: candidates are: Composition::Composition(int, int)
note:                 Composition::Composition()
note:                 Composition::Composition(Composition&)

I've got past this problem by defining my own copy constructor in Composition with an empty body for now.

I'm however still unsure why I had to create my own copy constructor in one case and was able to get by with the compiler generated one in the other. The culprit of course is the mutex. Is it the non-copyable property of ther mutex creating this issue or is it something else I'm missing?

1

There are 1 answers

0
Mohit Jain On BEST ANSWER

From this page

Class mutex

The mutex class is a model of Mutex and NonCopyable, and provides no additional facilities beyond the requirements of these concepts.

Because boost::mutex is NonCopyable, compiler won't generate a copy constructor if your class contains/inherits it as a member.