在C ++中返回指向本地/堆栈变量的指针 [英] Returning pointer to a local/stack variable in C++

查看:89
本文介绍了在C ++中返回指向本地/堆栈变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个functionx教程感到困惑....
<a href="http://www.functionx.com/cpp/examples/returnpointer.htm">http://www.functionx.com/cpp/examples/returnpointer.htm</a>[<a href="http://www.functionx.com/cpp/examples/returnpointer.htm" target="_blank" title="New Window">^</a>]
将返回指向myclass的本地对象的指针正确吗?该对象是否会在超出功能范围时被破坏...感到困惑....
我在msdn论坛中提出了问题...仍然不清楚...

http://social.msdn .microsoft.com/Forums/zh-CN/vclanguage/thread/75f14e6f-7e75-4d3a-abc0-b18514eed24c/?prof = required [

I am confused on this functionx tutorial....
<a href="http://www.functionx.com/cpp/examples/returnpointer.htm">http://www.functionx.com/cpp/examples/returnpointer.htm</a>[<a href="http://www.functionx.com/cpp/examples/returnpointer.htm" target="_blank" title="New Window">^</a>]
will returning a pointer to an local object of myclass is correct? will that object destroyed on going out of function scope... confused....
I raised the question in msdn forum... still not clear...

http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/75f14e6f-7e75-4d3a-abc0-b18514eed24c/?prof=required[^]

推荐答案

我不确定究竟是什么还不清楚……您似乎已经正确理解了-返回指向本地数据的指针并不安全,应该避免.没什么可添加的了.

要回答您的第二个问题:
恕我直言,该教程是错误的.
该类的副本构造函数将不会被调用.

顺便说一句-您不应将其他问题作为答案"发布-使用现有答案下的添加评论"链接来提出其他问题或评论其他人给您的答案.这样可以使线程保持清晰美观,以供所有人查看:)
I''m not sure what is unclear exactly... You seem to have gotten it right - returning pointers to local data is not safe and should be avoided. Nothing more to add really.

To answer your second question:
IMHO the tutorial is wrong.
The copy constructor of the class will not be called.

By the way - you should not post additional questions as ''answers'' - use the ''Add comment'' link under existing answers to ask additional questions or comment on the answers others give you. This keeps the thread nice and clear for everyone to view :)




您的 tutorial 是垃圾,不要在其他任何地方相信它.

此更改和其他类似更改将是正确的:
Hi,

Your tutorial is junk, don''t trust it anywhere else.

This, and other similar changes would be correct:
double * GetSalary()
{
    static double salary = 26.48;

    return &salary;
}


欢呼声,
AR


cheers,
AR


该教程是错误的:永远不要返回本地对象的地址.
:-)
The tutorial is wrong: never return the address of a local object.
:-)


这篇关于在C ++中返回指向本地/堆栈变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆