奇怪类型在c ++ [英] Strange type in c++
问题描述
我有一个方法与原型:
bool getAssignment(const Query& query,Assignment *& result);
我有点困惑第二个参数的类型( Assignment * & result
),因为我不认为我曾经看到过类似的东西。它的用法如下:
赋值* a;
if(!getAssignment(query,a))
return false;
它是指针的引用还是其他方法?或两者都不?任何解释赞赏。谢谢。
这是一个指针的引用。这个想法是能够改变指针。
$ b pre>
void f(char * p)
{
p = new char [100];
}
int main()
{
char * p_main = NULL;
f(p_main);
return 0;
}
不会更改 p_main
指向分配的字符数组(它是一个明确的内存泄漏)。这是因为你复制指针,它通过值传递(这就像传递一个 int
的值;例如 void f(int x)
!= void f(int& x)
)
所以,如果你改变 f
:
& p)
现在,这将通过 p_main
通过引用并将改变它。因此,这不是内存泄漏,在执行 f
后, p_main
将正确指向分配的内存。
PS同样可以通过使用双指针(例如, C
没有引用)来完成:
void f(char ** p)
{
* p = new char [100];
}
int main()
{
char * p_main = NULL;
f(& p_main);
return 0;
}
I have a method with the prototype:
bool getAssignment(const Query& query, Assignment *&result);
I am a bit confused about the type of the second param (Assignment *&result
) since I don't think I have seen something like that before. It is used like:
Assignment *a;
if (!getAssignment(query, a))
return false;
Is it a reference to a pointer or the other way around ? or neither ? Any explanation is appreciated. Thanks.
It's a reference to a pointer. The idea is to be able to change the pointer. It's like any other type.
Detailed explanation and example:
void f( char* p )
{
p = new char[ 100 ];
}
int main()
{
char* p_main = NULL;
f( p_main );
return 0;
}
will not change p_main
to point to the allocated char array (it's a definite memory leak). This is because you copy the pointer, it's passed by value (it's like passing an int
by value; for example void f( int x )
!= void f( int& x )
) .
So, if you change f
:
void f( char*& p )
now, this will pass p_main
by reference and will change it. Thus, this is not a memory leak and after the execution of f
, p_main
will correctly point to the allocated memory.
P.S. The same can be done, by using double pointer (as, for example, C
does not have references):
void f( char** p )
{
*p = new char[ 100 ];
}
int main()
{
char* p_main = NULL;
f( &p_main );
return 0;
}
这篇关于奇怪类型在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!