0

(assuming I cannot use boost::noncopyable, which was explicitly designed for that purpose)

(assuming I cannot use C++11)

When making a class noncopyable, I usually see the following syntax:

class MyClass
{
public:
    ...
    stuff
    ...

private:
    MyClass(const MyClass&); // disables the copy constructor
    MyClass& operator=(const MyClass&); // disables the copy assignment operator
};

This syntax seems long-winded. I think that I can use the following instead:

    MyClass(MyClass&); // disables the copy constructor
    void operator=(MyClass); // disables the copy assignment operator

This seems shorter (it repeats the name of the class just 3 times instead of 4 times; it also omits const and &).

Does my syntax do exactly the same thing as the other syntax?

Is there any reason to prefer one over the other?

anatolyg
  • 26,506
  • 9
  • 60
  • 134

1 Answers1

0

Putting the emphasize on shortening the source code a few words is not very good. Besides, you are making your operator= unreadible, it is no copy-operator anymore...
You should refrain from using the latter just to save a few words.

There is a post here, stating

//QUOTE

class MyClass
{
private:
    MyClass(const MyClass&) {}
    MyClass& operator=(const MyClass&) {}
};

If you are a C++ programmer who has read an introductory text on C++, but has little exposure to idiomatic C++ (ie: a lot of C++ programmers), this is... confusing. It declares copy constructors and copy assignment operators, but they're empty. So why declare them at all? Yes, they're private, but that only raises more questions: why make them private?

To understand why this prevents copying, you have to realize that by declaring them private, you make it so that non-members/friends cannot copy it. This is not immediately obvious to the novice. Nor is the error message that they will get when they try to copy it.

//QUOTE END

Community
  • 1
  • 1
bash.d
  • 13,029
  • 3
  • 29
  • 42