Can I modify the target of a pointer passed as parameter?

血红的双手。 提交于 2020-05-16 13:55:12

问题


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 &parameter)
{
    parameter = type("second");
}

type variable("first");
load(&variable);

That's easy but I try to do the same thing with pointers.


回答1:


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)
                ^
{



回答2:


You need to pass the pointer by reference:

void load(type *&parameter);

See for example http://www.cprogramming.com/tutorial/references.html




回答3:


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



来源:https://stackoverflow.com/questions/16276176/can-i-modify-the-target-of-a-pointer-passed-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!