Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why not return pointers or references to local objects in C++

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "Why do not return pointers or references to local objects in C++". The explanation in this article is simple and clear and easy to learn and understand. let's study and learn "Why don't return pointers or references to local objects in C++?"

Never return a pointer or reference to a local object, directly or indirectly.

Reason (reason)

To avoid the crashes and data corruption that can result from the use of such a dangling pointer.

To avoid crashes and data corruption caused by the use of this dangling pointer.

Example, bad (negative example)

After the return from a function its local objects no longer exist:

When the program exits from the function, the local variables in the function no longer exist.

Int* f () {int fx = 9; return & fx; / / BAD}

Void g (int* p) / / looks innocent enough {int gx; cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report