本文介绍了安全在C#中没有C ++的指针/引用简单的回报,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码C ++:
人* NewPerson(无效) {者P; / * ... * / 返回&安培; P; //返回指针的人。 }代码C#:
人NewPerson() {返回新人(); //返回参考的人。 }如果我理解这一权利,例如在C ++中,它也不行,因为' p'将走出去的范围,函数会返回一个野指针(悬摆指针)!(它可能工作一段时间)
和中C#它的确定,因为匿名新的人将留在范围,只要有它的参考。 (通过调用函数处理)
我有没有得到这个权利?
解决方案 人* NewPerson(无效) {人p(); / * ... * / 返回&安培; P; //返回指针的人。 }
P 不是一个人,看到的最伤脑筋的解析。因此,你会得到一个编译错误。
有关其余的,是的,你说得对。
Code c++:
person* NewPerson(void) { person p; /* ... */ return &p; //return pointer to person. }Code C#:
person NewPerson() { return new person(); //return reference to person. }If I understand this right, example in c++, its not ok because the 'p' will go out of scope, and the function will return a wild pointer(Dangling pointer) !(it may work for some time)
And in c# its ok because the anonymous 'New person' will stay in scope as long there is an reference to it. (handle by the calling function)
Did I get this right?
解决方案 person* NewPerson(void) { person p(); /* ... */ return &p; //return pointer to 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 ++的指针/引用简单的回报,
发布评论