开发者

Opt-out of copy constructor

This might be a silly question, but...

I've been writing a number of classes that utilize non-copyable members. T开发者_运维百科hese classes are never initialized via the copy constructor in my source. When I try to compile without supplying my own copy-constructor, g++ throws out many errors about how it can't build a default copy constructor, due to the non-copyable member objects.

Is there a way to tell the compiler to just not give me a copy constructor?

EDIT: Yeah... feels silly... I had a case where I was invoking the copy-constructor by accident in a boost::bind call. Lesson learned.


The usual way to make things noncopyable is to declare but not define a copy constructor, and make it private so nothing can call it.

The next revision of the language will provide an explicit way to suppress these generated functions.


If you don't actually cause the copy-constructor to be called then it is not an error if the compiler would be unable to generate one. It sounds like you are (possibly indirectly) causing the copy-constructor to be used.

You can suppress the compiler generated one by declaring your own copy-constructor (you don't need to define it if you're not using it). You can place it in the private section of your class.

If this changes the error to say that the copy-constructor is inaccessible or you get link errors then you really are causing the copy-construtor to be used and you need to analyze why this is.


Not in the current version of C++. In C++ 0x, there will be an =delete; syntax to tell it that you don't want one of the special member functions the compiler will generate by default if you don't defined one yourself.


Until the new C++ 0x standard is fully supported, the best you can do is to delclare a version of the special member function, but not implement them. Normally they are made private (to help make it clear that they shouldn't be used).


Class foo
{
    // ... rest of definition
    private:
        foo (const foo& rhs); // Do Not Implement
        const foo& operator= (const foo& rhs); // Do Not Implement
};


No :)

If you want your class to be non-copyable use something like boost::noncopyable

class MyClass : private boost::noncopyable
{

}

or use a parametrizied macro in your class definition that declares a private copy constructor.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜