I want to do the opposite of making instances of a class noncopyable
, that is, make sure that instances of a particular class can be passed only as a c
I dont think making operator & private is going to do it, is there a legitimate way of doing this.
No, because the &
you use in function signatures for pass-by-reference is not an operator. You're talking either about the address-of operator (unary) or bitwise-and operator (binary). So it has nothing to do with pass-by-reference.
There's no way to disallow pass-by-reference for a type.
I doubt your motivation is strong enough to do this, and you appear to have a bad understanding of the passing mechanism:
If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.
A function either passes a parameter by reference, or by value. It's decided by its declaration, and I think your confusion stems from here. For example:
void foo(X x);
takes the parameter x
by value. There's no way to pass it by reference. No way. Likewise:
void foo(X& x)
takes it by reference, and it always will.
That's impossible. Any named variable can bind to a reference variable of the appropriate type. That's just how the language works.
In particular, you could never have a copy constructor with your restriction, so you couldn't actually pass the object by value!