Preventing compilers from defining copy constructo

2019-06-20 07:40发布

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

标签: c++ class
7条回答
相关推荐>>
2楼-- · 2019-06-20 08:02

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.

查看更多
▲ chillily
3楼-- · 2019-06-20 08:04

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

Or...have a reference member variable :P

查看更多
聊天终结者
4楼-- · 2019-06-20 08:05

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)
};
查看更多
来,给爷笑一个
5楼-- · 2019-06-20 08:07

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

查看更多
神经病院院长
6楼-- · 2019-06-20 08:07

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.

查看更多
一纸荒年 Trace。
7楼-- · 2019-06-20 08:08

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.

查看更多
登录 后发表回答