开发者

Preventing compilers from defining copy constructors and operator = overload for C++ Classes

Is there a way by which we can prevent compilers from defining copy constructo开发者_运维百科rs, operator = overload for C++ classes.


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.


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).


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.


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.


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).


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

Or...have a reference member variable :P


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)
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜