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.
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.
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.
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.
The the reference ends its lifetime before the object does, then... well, nothing happens. The reference disappears, the object continues to live.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With