I am not a fan of copy construction. Too many times, I've written
void MyFunc(MyClass val)
instead of
void MyFunc(const MyClass& val)
and had to spend hours debugging bugs around pointers having been deleted in the passed-by-value clone's destructor, or discovering slowdown because I'm copying every member of MyClass every time I call MyFunc.
So I don't want to allow copy constructors.
I know you can ban them on a per-class basis with
private:
MyClass(const MyClass&)
But I don't want to have to do that on every single class.
Is there a compiler switch to turn off copy construction by default? Is there a reason I should allow copy construction on anything other than built-in types and pointers? (These same questions apply to copy assignment, too)
Is there a compiler switch to turn off copy construction by default?
No, and I really I hope there isn't. Fortunately, to the best of my knowledge, that's indeed the case.
Is there a reason I should allow copy construction on anything other than built-in types and pointers?
Sure. For instance, to give your types value semantics and treat different instances of your class as the same conceptual entity. And in that case, creating copies turns out to be quite a handy thing.
If you want to have a non-copyable class, on the other hand (there are use cases for this), you can declare the copy-constructor as private
(as you yourself suggested) or, in C++11, mark it as deleted:
struct X
{
X(X const&) = delete;
};
Concerning what you write:
Too many times, I've written
void MyFunc(MyClass val)
instead ofvoid MyFunc(const MyClass& val)
and had to spend hours debugging bugs
I understand that you may make mistakes, but you have to learn from them. You could also write an ordinary function such as foo()
below:
void foo(int x) { x++; }
And swear for hours trying to figure out why, when you pass it as an argument a variable whose value is 3
, the value of that variable after the call returns is not 4
. Oh, you forgot to add the reference symbol:
void foo(int& x) { x++; }
// ^
Now is this a reason for desiring a compiler option that would make pass-by-reference the default? Not really. That would be an option to change the language rules.
Imagine would would happen if your compiler really had such a switch you are wishing for, and one day you would send your program to someone else who is not using that switch: how many hours would they spend debugging it to find out where the problem is?
My advice is to learn from experience and try to adapt your reading and writing skills to the Standard language, rather than vice versa.