简体   繁体   English

我可以修改作为参数传递的指针的目标吗?

[英]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);

In this minimal example, will pointer point to the second allocate object? 在这个最小的示例中, pointerpointer第二个分配对象吗? 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. 这很容易,但是我尝试使用指针做同样的事情。

No. 没有。

parameter will get a copy of the value of pointer in this case. 在这种情况下, parameter将获取pointer值的副本。 So it is a new variable. 因此,这是一个新变量。 Any change you make to it is only visible with in the function scope. 您对其所做的任何更改仅在功能范围内可见。 pointer stays unmodified. pointer保持不变。

You have to pass the pointer by reference 您必须通过引用传递the pointer

void load(type *& parameter)
                ^
{

You need to pass the pointer by reference: 您需要通过引用传递指针:

void load(type *&parameter);

See for example http://www.cprogramming.com/tutorial/references.html 参见例如http://www.cprogramming.com/tutorial/references.html

Alternatively, you can use double pointers. 或者,您可以使用double指针。

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 但是由于您使用的是cpp,因此可以使用references

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM