我可以修改作为参数传递的指针的目标吗? [英] Can I modify the target of a pointer passed as parameter?
问题描述
函数可以更改作为参数传递的指针的目标,以使效果保持在函数外部吗?
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);
在这个最小的示例中,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.
推荐答案
否.
parameter
将获得pointer
值的副本.因此,这是一个新变量.您对其所做的任何更改仅在功能范围内可见. pointer
保持不变.
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.
您必须通过引用传递the pointer
void load(type *& parameter)
^
{
这篇关于我可以修改作为参数传递的指针的目标吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!