Can a function change the target of a pointer passed as parameter so that the effect remains outside the function?
void load(type *parameter)
{
delete parameter;
parameter = new type("second");
}
type *pointer = new type("first");
load(pointer);
In this minimal example, will pointer
point to the second allocate object? If not, how can I get this kind of behavior?
Update: To clarify my intention, here is the code I would use if the parameter would be a normal type instead of a pointer. In this case I would simply use references.
void load(type ¶meter)
{
parameter = type("second");
}
type variable("first");
load(&variable);
That's easy but I try to do the same thing with pointers.
No.
parameter
will get a copy of the value of pointer
in this case. So it is a new variable. Any change you make to it is only visible with in the function scope. pointer
stays unmodified.
You have to pass the pointer
by reference
void load(type *& parameter)
^
{
You need to pass the pointer by reference:
void load(type *¶meter);
See for example http://www.cprogramming.com/tutorial/references.html
Alternatively, you can use double
pointers.
void load(type** parameter)
{
delete *parameter;
*parameter = new type("second");
}
type *pointer = new type("first");
load(&pointer);
But since you are using cpp you can use references
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.