安全在C#中没有C ++的指针/引用简单的回报,

编程入门 行业动态 更新时间:2024-10-27 00:35:22
本文介绍了安全在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 ++的指针/引用简单的回报,

本文发布于:2023-07-29 10:58:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1240071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!