将本地 CStringW 返回给调用者是否安全?

发布于 2024-09-13 19:13:41 字数 63 浏览 3 评论 0原文

我有一个函数定义了一个在 CStringW 中键入的局部变量,通过值而不是通过引用将该对象返回给调用者是否安全?

I have a function defined a local variable typed in CStringW, is it safe to return this object to the caller by value, not by reference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠意 2024-09-20 19:13:41

是的,应该没问题。 CString 内部使用带有引用计数的缓冲区并执行写入时复制,因此当您创建 CString 的副本然后销毁原始对象时,一切都应该“只是工作”。

Yes, it should be ok. CString internally uses a buffer with reference counting and does copy-on-write, so that when you create a copy of CString and then destroy the original object, everything should "just work".

太阳男子 2024-09-20 19:13:41

我相信 CString 来自 MFC,而不是 STL,因此您可能需要更改标签。

如果您从函数返回局部变量,则按值返回是安全的,但按引用返回安全。按值返回有效地将字符串复制到调用者。通过引用返回为调用者提供了对局部变量的引用,该变量在函数返回时被销毁 - 因此调用者永远无法使用它,并且返回的引用始终无效。

I believe CString is from MFC, not STL, so you might want to change your tags.

If you're returning a local variable from a function, it's safe to return by value, but not safe to return by reference. Returning by value effectively copies the string to the caller. Returning by reference gives the caller a reference to the local variable which is destroyed when the function returns - so the caller can never use it, and the returned reference is always invalid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文