Alex Rivera | Logout

compiler generated constructors

Asked 2010-03-04T16:07:39.227
13

This is just a quick question to understand correctly what happens when you create a class with a constructor like this:

class A
{
  public:
    A() {}
};

I know that no default constructor is generated since it is already defined but are copy and assignment constructors generated by the compiler or in other words do i need to declare a private copy constructor and a private assignment operator in order to prevent this from happening?

class A
{
  private:
    // needed to prevent automatic generation?
    A( const A& );
    A& operator=( const A& );
  public:
    A() {}
};
Edit
Report

1 Answer

3

If you want to disable copying and assigning, then it might be better to inherit from a class that has a private copy constructor and assignment operator (boost::noncopyable is a ready-made one).

1) Less repetitive typing.

2) Self-documenting (hopefully).

3) Stronger checks that those operations can't be invoked (the class itself, nor the friends can make copies either - that would result in a compiler, not a linker error).

4) Won't hide the default constructor :)

#include <boost/noncopyable.hpp>

class X : boost::noncopyable
{
};

int main()
{
    X a, b;     //has default constructor
    //X c(a);   //but can't be copied
    //a = b;    //or assigned
}
answered 2010-03-04T21:02:02.267

Your Answer