Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to disallow taking a reference to an object

Tags:

c++

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.

like image 346
san Avatar asked Nov 05 '12 16:11

san


People also ask

Can we pass objects by reference?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

Can reference be modified?

Formally speaking, that is impossible as it is forbidden by design. Arbitrarily speaking, that is possible. A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address.

What happens when we pass an object by reference?

When an object (or built-in type) is passed by reference to a function, the underlying object is not copied. The function is given the memory address of the object itself. This saves both memory and CPU cycles as no new memory is allocated and no (expensive) copy constructors are being called.

Do references go out of scope?

The the reference ends its lifetime before the object does, then... well, nothing happens. The reference disappears, the object continues to live.


1 Answers

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!

like image 115
Kerrek SB Avatar answered Sep 30 '22 13:09

Kerrek SB