Preventing compilers from defining copy constructo

2019-06-20 07:58发布

问题:

Is there a way by which we can prevent compilers from defining copy constructors, operator = overload for C++ classes.

回答1:

You can declare these functions as private which prevents people from using them when working with your class and at the same time prevents the compiler from generating them.



回答2:

Yes. Derive from boost::noncopyable.

(There're also NIH ways to do that, by declaring the private never-defined methods for operator= and copy constructor, but, please love boost).



回答3:

Declare those functions yourself and make them private. Also you can didn't write definitions of that functions, so everyone who try to use those functions - will get an linker error.



回答4:

In C++0x, you'll be able to write

class NonCopyable {
  NonCopyable & operator=(NonCopyable const&) = delete;
  NonCopyable(NonCopyable const&) = delete;
};

Note that the compiler will not generate converting NonCopyable::operator=(Other const&) overloads in any case.



回答5:

Defining? Well, yes. They are always declared (explicitly by you or implicitly by the compiler), but they are only defined by the compiler when/if you actually use them. Don't use them - and the compiler will not define them.

Of course, if by "prevent compilers from defining ...", you mean "prevent compilers from successfully defining...", i.e. if you want to make the implicit definition attempt fail at compile time, then you can achieve that by adding non-copy constructible and/or non-assignable subobject to your class (like a base or member with private copy-constructor and private assignment operator, for example).



回答6:

Inherit from a type that declares those functions in the private scope, such as boost::noncopyable.

Or...have a reference member variable :P



回答7:

FWIW if you ever get around to using Qt then you can use the Q_DISABLE_COPY macro:

class Foo
{
public:
  Foo();

private:
  Q_DISABLE_COPY(Foo)
};


标签: c++ class