Reputation: 75130
Is it possible to define a function which will make the argument refer to another (already existing) object after it returns without using pointers, etc? Again, this can't just change the existing object by using a copy constructor or assignment operator or anything. The outside object would refer to a different block of memory when the function returned.
For example:
int x;
void change(int& blah) {
blah = x; // I don't want to change blah's value to x's value, I want to make blah refer to x outside the function
}
void main() {
int something = 0;
change(something);
assert(&x == &something);
}
Regardless of the method used, the function must be called like
change(x);
Without applying any special operator or function to the argument before calling the function. I don't know if this is possible, but it would make very cool things possible if it is. If it's not, I would also like to know why.
Upvotes: 0
Views: 188
Reputation: 19339
Nope definitely not possible. Both regular variables like int x
and references variables like int &y(...)
and arrays are not reseatable, i.e. they always will use/point to the same chunk of memory.
To obtain the functionality you require, you really need to either use a pointer, or an abstraction of pointers. It's not possible otherwise.
As an attempt at an explanation, here goes (not entirely correct, and grossly simplified, but good enough to get the idea):
When you declare a variable like int x
, you are really asking for the compiler to associate x
with a specific region of memory. So, for example, suppose x
is associated the four-byte starting at 0x439FC2
. Since the compiler knows that x
should always refer to 0x439FC2
, than any use of x
can really be replaced by looking up those memory cells, and loading them into registers, pushing them onto the stack, or whatever. Anyways, the end result is that the variable name x
is pretty much replaced by the number 0x439FC2
. So the reason you can't move x
around is that you can't make that memory address refer to a different location in memory.
Again, that explanation is simplified and not entirely true, but it is the "intuitive" way of reasoning about automatically allocated variables.
Upvotes: 1
Reputation: 5136
You want to use a reference to a pointer:
void change(int &* blah, int * x){
blah = x;
}
int * num1;
int num2 = 2;
change( num1, &num2 ); //num1 now points to num2
Upvotes: 0
Reputation: 355019
No, because something
and x
are different objects. They don't refer to different objects. They don't point to different objects. They are different objects.
To change where something points, that something needs to be a pointer. If you have a pointer, you can do this:
int x;
void change(int*& p)
{
p = &x;
}
int main()
{
int something = 0;
int* pointer = &something; // pointer points to 'something'
change(pointer); // now pointer points to 'x'
assert(&x == pointer);
}
Upvotes: 5