函数声明中的“*&"是什么意思?

2022-01-05 00:00:00 reference pointers c++

我写了一个类似这样的函数:

void myFunc(myStruct *&out) {out = 新的 myStruct;out->field1 = 1;out->field2 = 2;}

现在在调用函数中,我可能会这样写:

myStruct *data;myFunc(数据);

这将填充data中的所有字段.如果我在声明中省略了 '&',这将不起作用.(或者更确切地说,它只会在函数中本地工作,但不会改变调用者的任何内容)

有人可以向我解释这个*&"实际上是做什么的?看起来很奇怪,我就是无法理解.

解决方案

The &C++ 变量声明中的符号表示它是一个引用.>

它恰好是一个指针的引用,它解释了你所看到的语义;被调用的函数可以改变调用上下文中的指针,因为它有一个对它的引用.

所以,重申一下,这里的操作符号"不是 *&,这种组合本身并不意味着很多.*myStruct * 类型的一部分,即指向 myStruct 的指针",而 & 使得它是一个引用,因此您可以将其读作out 是对指向 myStruct 的指针的引用".

在我看来,最初的程序员可以这样写:

void myFunc(myStruct * &out)

甚至(不是我个人的风格,但当然仍然有效):

void myFunc(myStruct* &out)

当然,关于风格还有很多其他的意见.:)

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. :)

相关文章