本文介绍了在C#中安全,但在C ++中不安全,简单返回指针/引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++代码:
person* NewPerson(void)
{
person p;
/* ... */
return &p; //return pointer to person.
}
C#代码:
person NewPerson()
{
return new person(); //return reference to person.
}
如果我理解此权利,则C ++中的示例不正确,因为p
将超出范围,该函数将返回一个野生指针(悬空指针).
If I understand this right, the example in C++ is not OK, because the p
willgo out of scope, and the function will return a wild pointer (dangling pointer).
C#中的示例是可以的,因为只要有匿名新人的引用,它就会一直在作用域内. (调用函数得到一个.)
The example in C# is OK, because the anonymous new person will stay in scope as long as there is a reference to it. (The calling function gets one.)
我说对了吗?
推荐答案
person* NewPerson(void)
{
person p();
/* ... */
return &p; //return pointer to person.
}
p
不是person
,请参见.这样,您会得到一个编译器错误.
p
is not a person
, see most vexing parse. As such, you'd get a compiler error.
其余的,是的,你是对的.
For the rest, yes you're right.
这篇关于在C#中安全,但在C ++中不安全,简单返回指针/引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!