What's the simplest way to emulate = delete in C ++ 03 to restrict copy / assignment operations?

C ++ 11 scratches the itch that has bothered me for a long time, allowing you to implicitly compile certain methods as verboten with the "= delete" syntax. Wikipedia for more information.

class Foo
{
public:
     Foo();
    ~Foo();

    // No copy
    Foo(Foo const &) = delete;
    Foo& operator=(Foo const &) = delete;
};

      

Copy and assignment operators for classes that I don't expect to be copied or assigned are always pains to run into. It's a lot of boilerplate code to make it private, and then there are often data members that don't have a default constructor that require some hand waving to make the compiler happy on a function you just don't want anyone to ever call ...

class Bar
{
public:
   explicit Bar(UniqueResourceID id): m_data(id) { }
   ~Bar();

protected:
   SomeHandle  m_data; // no default constructor

// all this crap to keep from being able to copy.  Do not use any of these!!
private:
   Bar() { } // ERROR: m_data has no default constructor
   static UniqueResourceID s_invalidID; // now I'm making the problem worse,
                                        // because I don't actually need this
                                        // for anything real, except to shut
                                        // up some errors.
   Bar(Bar const &o): m_data(s_invalidID) { }
   Bar& operator =(Bar const &o): { return *this; }
};

      

Unfortunately, some of the compilers I have to use are not C ++ 11 compilers and do not offer = delete. What's the best way to handle this? (Please tell me a better way than the second code snippet.)

+3


source to share


1 answer


You are writing all the extra crap because you are actually defining the body of the statements deleted

- I don't think you need it, and what I am doing is just making a declaration without any implementation like this;

class Bar
{
public:
   explicit Bar(UniqueResourceID id): m_data(id) { }
   ~Bar();

protected:
   SomeHandle  m_data; // no default constructor

private:
   Bar(); 
   Bar(Bar const &o);
   Bar& operator =(Bar const &o);
};

      

It is no more verbose than casting a method from = delete

.



Edit: your definition

....
private:
   Bar() {}

      

In fact dangerous, because it allows the operator to be called from other methods in Bar

without any errors occurring when creating (linker or compiler)

+6


source







All Articles