In my project, there is a definition of a function call like this.
int32 Map(void * &pMemoryPointer)
In the calling place, the paramenter passed is void*, why cant we just receive it as a pointer itself, instead of this?
Without knowing what the Map function does, I'd guess that it sets the pointer. Therefore it has to be passed by reference.
Using a reference to a pointer, you can allocate memory and assign it to the pointer inside the function. For example
void DoSomething(int*& pointerReference)
{
// Do some stuff...
pointerReference = new int[someSize];
// Do some other stuff...
}
The other way to make functions like that is to return the pointer, but as the Map function in the question returns something else that can't be used.
Reading it backwards, this means that pMemoryPointer is a reference (&) to a pointer (*) to void. This means that whatever pointer you pass gets referenced, and any modification that the function will do to pMemoryPointer will also affect the original (passed) pointer (e.g. changing the value of pMemoryPointer will also change the value of the original pointer).
why cant we just receive it as a pointer itself, instead of this?
That's because by doing that, you are copying the pointer and any change that you'll make to the copy doesn't reflect to the original one.
void im_supposed_to_modify_a_pointer(void* ptr) { // Oh no!
ptr = 0xBADF00D;
}
int* my_ptr = 0xD0GF00D;
im_supposed_to_modify_a_pointer(my_ptr);
ASSERT(my_ptr == 0xBADF00D) // FAIL!
That's a weird function prototype IMHO, but it means
(Update) that the Map function accepts a reference to a void pointer as a parameter.
So I think, it is equivalent to declaring the function like this:
int32 Map(void** pMemoryPointer)
Related
I have a struct, say:
struct Astruct {
int a;
int b;
}
And I have av instance of that struct say:
private:
Astruct My_List;
Then I have a function that I want to get the address of My_List.
public:
void Get_My_List(Astruct* List) {
List = &My_List;
}
However it seems to always set the argument Astruct* List = 0;
I know I probably could make a function called Astruct& Get_Address() or something but in this particular case I would like to know why I can't assign addresses in the argument. I mean it is possible to pass arguments as references and change the data. Or maybe I start to understand the problem now when I write this... Anyway just to be sure, is it possible to change the address the pointer points to via an argument? Or can I just change the data the pointer points to?
I figured it out. Yes it was about confusion, but not pointer confusion, more like argument confusion!
So the problem is that I thought I could "return" values via arguments. I thought that because I have previously created functions that takes a pointer and then the function changes the data the address points to. And yes it is "set" to zero. I mean #john is right, the code can't set it, but it is never changed. Because the value I pass in is initialized to zero and I can't change an argument, in this case Astruct* List. So the pointer I pass remains unchanged.
So what I had to do was to make the function take a pointer to a pointer.
void Get_My_List(Astruct** List) {
*List = &My_List;
}
And pass the address to the pointer instead. In that case I can change the data the pointer points to, which is a pointer.
Thanks, bye!
You can pass the reference-to-pointer:
void Get_My_List(Astruct*& List) {
List = &My_List;
}
and call it like that:
AstructHolder obj{};
Astruct* my_ptr{nullptr};
obj.Get_My_List(my_ptr);
I don't understand the 2nd argument.
Whats is it exactly?
And most importantly he(the programmer) uses it to create a new array of Object objects , of num (the variable) size at the end.
void expand(const Object &s, Object* &children, int &num)
{
...
children = new Object[num]; // <----
}
Read it from right to left:
When you reach a *, replace it by pointer to.
When you reach a &, replace it by reference of.
So children will be:
A reference of a pointer to an Object.
Second argument: Object* &children
Object* says that children is a pointer to Object type.
& prevent from receiving a copy of children from calling scope and lets us to work directly with argument variable, so when you change children :
children = new Object[num];
you change the argument variable in calling scope and after expand function returns, you have access to:
new Object[num]
via the argument variable that you passed to expand function.
Passing arguments by reference, is another way to receive information from function (It has other usages too).
It's:
a reference of a pointer to an Object
The reason is that because it allocates dynamically memory, he probably wants this change to children to be reflected in the caller of the function (probably main()).
Imagine a function like this:
function(Human *&human){
// Implementation
}
Can you explain what exactly a *& is? And what would it be used for? How is different than just passing a pointer or a reference? Can you give a small and explanatory sample?
Thank you.
It is like a double pointer. You're passing the pointer by reference allowing the 'function' function to modify the value of the pointer.
For example 'human' could be pointing to Jeff and function could modify it to point to Ann.
Human ann("Ann");
void function(Human *& human)
{
human = &ann;
}
int main()
{
Human jeff("Jeff");
Human* p = &jeff;
function(p); // p now points to ann
return 0;
}
void doSomething(int &*hi);
will not work. You cannot point to references. However, this:
void doSomething(int *&hi); // is valid.
It is a reference to a pointer. This is useful because you can now get this pointer passed into the function to point to other "Human" types.
If you look at this code, it points "hi" to "someVar". But, for the original pointer passed to this function, nothing will have changed, since the pointer itself is being passed by value.
void doSomething(int *hi)
{
hi = &someVar;
}
So you do this,
void doSomething(int *&hi)
{
hi = &someVar;
}
So that the original pointer passed into the function is changed too.
If you understand "pointers to pointers", then just imagine that, except when something is a reference it can be treated like a "non-pointer".
"Takes an address of a pointer" - No, it doesn't. It takes supposed to take a reference to a pointer.
However, this is a syntax error. What you probably meant is
rettype function(Human *&human)
(Yes, it's also missing a return type...)
Since you wrote this code off the top of your head, I'm going to assume you meant to do something like this:
void f(T *&) {}
This function signature allows the pointer passed to become modifiable, something that isn't allowed with the alternate syntax int *. The pointer is effectively passed by reference as others here call it.
With this syntax, you are now able to modify the actual pointer and not just that which it points to. For example:
void f(int *& ptr) {
ptr = new int;
}
int main() {
int * x;
f(ptr); // we are changing the pointer here
delete x;
}
Summary (assume types are in parameters):
T *: We are only able to change the value of the object to which the pointer points. Changing the parameter will not change the pointer passed.
T *&: We can now change the actual pointer T, and the value of the object to which it points *T.
Even though it looks just like the address-of operator, it's not - it's a reference parameter. You use a reference when you want to be able to change the value at the caller's end. In this case the pointer is probably being set or changed within the function.
Lets say I have a class "A" and this function:
void initializationFunction(A* classPointer)
{
...
...
classPointer = new A(.....);
}
I write:
A* classPointer;
Then I pass this pointer to this function:
initializationFunction(classPointer);
This will not work unless I pass it by reference in the function declaration:
void initializationFunction(A*& classPointer);
I thought reference passing was for non-pointer type variables. I mean you don't need to pass an array by reference...
Thanks for the explanations :)
Yeah, that is true. You've to pass the argument by reference (or you can pass A** instead).
But the best solution is to write the constructor of A in such way that you wouldn't need this function in the first place. That is, whatever you're doing in this function, you should be doing that in the constructor itself.
If, however, you cannot edit the class, then you can do this instead:
A *initializationFunction()
{
A *obj = new A(.....);
//...
return obj;
}
A *classPointer = initializationFunction();
In my opinion, this approach is better than yours.
Note I didn't change the name of the function and other variables. I guess that isn't the point of the post. But I believe you would want better names for real code.
Either you declaration with the reference or the following one will do:
void initializationFunction(A** classPointer);
The point is that you are passing in a pointer argument and that you want to modify the value it had in the caller. This is an out parameter and out parameters should be passed by reference, not by value (reference here means either through a pointer or reference). This out parameter is a pointer, so you should pass a pointer to that pointer or a reference to that pointer.
In other words, you need to access the original argument in the caller stack to be able modify it. In the declaration
void initializationFunction(A* classPointer);
classPointer is akin to a local variable defined inside of initializationFunction and is just a copy of the classPointer you allocated in the caller function. Modifying a copy of classPointer will not modify the original variable, so you need a pointer to the original variable to be able to modify it. The same holds true if you use a reference to the original classPointer.
An alternative approach you have is returning the new classPointer from your function:
A* initializationFunction(void);
in this case the caller would simply do:
A* classPointer = initializationFunction();
You can pass any variable by reference. The difference between passing by reference and passing by value, is that when you pass by reference, you are in fact passing the very same pointer that is pointing to the value in that memory location, and when you pass by value you are just passing another reference to that memory location, and therefore anything you assign to it will NOT change the value of the parameter passed.
Either use a double pointer (a**) or a reference as you did.
In your first example, the pointer is passed by value (ie. the function gets a copy of the pointer). The object that the pointer points to is of course the same both in the calling code and inside the function.
In the second example, the pointer is passed by reference (ie. the function basically uses the same pointer as the calling code).
say you had a windows shortcut pointing to a text file in "My Documents".
you can copy that shortcut and paste it anywhere in windows, double click on it, and it opens the text file in "My Documents". That is passing by reference / pointer. The shortcut points to "where", then you use it to change the "stuff".
However, the code you posted doesn't "open" the file pointed to by the shortcut. It actually changes the shortcut to point to (actually create ) a new "file". But since the shortcut itself was first copied ( passed by value ), the effect is that you allocated memory but cannot access it. So analogously you changed the shortcut, created a "file", but then deleted the directory with that shortcut in there ( but your file is then lost in outer space !).
Unfortunately, there is really no analogy for passing a shortcut itself by reference, you would basically have to copy the shortcut back out of the directory, then replace the original text file in "my documents" with a shortcut to this new "file". Hope this helps instead of confuses it further :(.
The reason you have to pass the pointer by reference is that you're actually changing where in memory it points to. If you had already assigned it to an object and wanted to modify that object, passing it directly to the function would be fine.
When you do a Aptr = new A(...), you are
- Creating an 'A' object somewhere on the heap
- Assigning the address of the newly created object to Aptr
If the function doesn't have a reference to Aptr, the function can't change its value.
You can pass pointers by reference because pointers are also variables with their own address.
For example, in a 32-bit architecture, you can declare an unsigned int and use it as a pointer.
This is normal.
I explain:
void foo(X* toto)
{
toto=new X();
}
toto value will be poped out from call stack with it's initial value (as any other argument , pointer or not)
since it's not possible to change function argument value UNLESS it's a reference.
so:
void foo(X*& toto)
{
toto=new X();
}
Here you explicitely say toto argument as being X*& (X* for type , and & (reference) to let it's value be modified inside function foo)
Pointer types are the same than any other types. replace X* by int and you'll immediately find that toto won't be changed outside of function call unless passed as reference.
An X** would also have done the trick , using such implementation:
void foo(X** toto)
{
*toto=new X();
}
It should be:
void initializationFunction(A** classPointer)
{
...
...
*classPointer = new A(.....);
}
Call:
initializationFunction(&ptr);
the function will set the argument passed in to the new A(......);
example: http://ideone.com/u7z6W
I wrote a function along the lines of this:
void myFunc(myStruct *&out) {
out = new myStruct;
out->field1 = 1;
out->field2 = 2;
}
Now in a calling function, I might write something like this:
myStruct *data;
myFunc(data);
which will fill all the fields in data. If I omit the '&' in the declaration, this will not work. (Or rather, it will work only locally in the function but won't change anything in the caller)
Could someone explain to me what this '*&' actually does? It looks weird and I just can't make much sense of it.
The & symbol in a C++ variable declaration means it's a reference.
It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it.
So, to reiterate, the "operative symbol" here is not *&, that combination in itself doesn't mean a whole lot. The * is part of the type myStruct *, i.e. "pointer to myStruct", and the & makes it a reference, so you'd read it as "out is a reference to a pointer to myStruct".
The original programmer could have helped, in my opinion, by writing it as:
void myFunc(myStruct * &out)
or even (not my personal style, but of course still valid):
void myFunc(myStruct* &out)
Of course, there are many other opinions about style. :)
In C and C++, & means call by reference; you allow the function to change the variable.
In this case your variable is a pointer to myStruct type. In this case the function allocates a new memory block and assigns this to your pointer 'data'.
In the past (say K&R) this had to be done by passing a pointer, in this case a pointer-to-pointer or **. The reference operator allows for more readable code, and stronger type checking.
It may be worthwhile to explain why it's not &*, but the other way around. The reason is, the declarations are built recursively, and so a reference to a pointer builds up like
& out // reference to ...
* (& out) // reference to pointer
The parentheses are dropped since they are redundant, but they may help you see the pattern. (To see why they are redundant, imagine how the thing looks in expressions, and you will notice that first the address is taken, and then dereferenced - that's the order we want and that the parentheses won't change). If you change the order, you would get
* out // pointer to ...
& (* out) // pointer to reference
Pointer to reference isn't legal. That's why the order is *&, which means "reference to pointer".
This looks like you are re-implementing a constructor!
Why not just create the appropriate constructor?
Note in C++ a struct is just like a class (it can have a constructor).
struct myStruct
{
myStruct()
:field1(1)
,field2(2)
{}
};
myStruct* data1 = new myStruct;
// or Preferably use a smart pointer
std::auto_ptr<myStruct> data2(new myStruct);
// or a normal object
myStruct data3;
In C++ it's a reference to a pointer, sort of equivalent to a pointer to pointer in C, so the argument of the function is assignable.
Like others have said, the & means you're taking a reference to the actual variable into the function as opposed to a copy of it. This means any modifications made to the variable in the function affect the original variable. This can get especially confusing when you're passing a pointer, which is already a reference to something else. In the case that your function signature looked like this
void myFunc(myStruct *out);
What would happen is that your function would be passed a copy of the pointer to work with. That means the pointer would point at the same thing, but would be a different variable. Here, any modifications made to *out (ie what out points at) would be permanent, but changes made to out (the pointer itself) would only apply inside of myFunc. With the signature like this
void myFunc(myStruct *&out);
You're declaring that the function will take a reference to the original pointer. Now any changes made to the pointer variable out will affect the original pointer that was passed in.
That being said, the line
out = new myStruct;
is modifying the pointer variable out and not *out. Whatever out used to point at is still alive and well, but now a new instance of myStruct has been created on the heap, and out has been modified to point at it.
As with most data types in C++, you can read it right-to-left and it'll make sense.
myStruct *&out
out is a reference (&) to a pointer (*) to a myStruct object. It must be a reference because you want to change what out points at (in this case, a new myStruct).
MyClass *&MyObject
Here MyObject is reference to a pointer of MyClass. So calling myFunction(MyClass *&MyObject) is call by reference, we can change MyObject which is reference to a pointer. But If we do myFunction( MyClass *MyObject) we can't change MyObject because it is call by value, It will just copy address into a temporary variable so we can change value where MyObject is Pointing but not of MyObject.
so in this case writer is first assigning a new value to out thats why call by reference is necessary.