san
san

Reputation: 4254

Is it possible to disallow taking a reference to an object

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 copy and not as a reference. If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.

I dont think making operator & private is going to do it, is there a legitimate way of doing this.

Upvotes: 20

Views: 3013

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258568

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.

Upvotes: 7

Kerrek SB
Kerrek SB

Reputation: 476970

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!

Upvotes: 22

Related Questions