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

What is the reason for using pointer objects in C++?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the C++ pointer object in the use of the reason is what the relevant knowledge, detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that we read this C++ pointer object in the use of the reason is what the article will be harvested, let's take a look at it.

problem description

When I use C++ for object-oriented development, I find a problem that puzzles me very much: C++ often uses object pointers instead of directly using the object itself, such as the following example:

Object *myObject = new Object;

Instead of using:

Object myObject;

Either this is not used when calling an object's method (e.g. testFunc()):

myObject.testFunc();

Instead, it has to be written like this:

myObject->testFunc();

I don't understand why the code should be written in this form, what I can think of is pointer mode is direct access to memory, so writing code can improve code efficiency and execution speed, is this it?

Best response from Joseph Mansfield

Unfortunately, you encounter so much dynamic memory allocation in your code, but this only shows that there are too many unqualified C++ programmers out there.

Put it this way, your two questions are essentially the same question. The first question is, when should dynamic allocation be used (using the new method)? The second question is, when should I use pointers?

The first important thing to remember is that you should choose the right method according to your actual needs. In general, it is more reasonable and safe to use defined objects than to use manual dynamic allocation (or new pointers).

dynamic allocation

The main difference between the two ways of allocating objects listed in your question is the lifetime of the objects. Objects are defined by Object myObject, and the lifetime of the object is automatic storage within its scope, which means that after the program leaves the scope of the object, the object will be automatically destroyed. When an object is allocated via new Object(), its lifetime is dynamic, meaning that it will always exist unless explicitly detete the object. You should only use dynamically allocated objects when necessary. In other words, whenever possible, you should prefer to define self-maintainable objects.

Here are two common situations where dynamic object allocation is required:

Allocate scope-unrestricted objects that are stored in their specific memory, rather than storing copies of objects in memory. If the object is copyable/removable, you should generally choose to use the defined object method.

The objects defined consume a lot of memory and may run out of stack space. It would be nice if we never had to think about this problem (in most cases, we really don't), because it's out of C++ itself, but unfortunately we have to deal with it in our actual development process.

When you do need to dynamically allocate objects, you should encapsulate them in a smart pointer or other type that provides RAII mechanisms (similar to standard containers). Smart pointers provide ownership semantics for dynamic objects, as exemplified by std::unique_ptr and std::shared_ptr. If you use it properly, you can basically avoid managing your own memory (see Rule of Zero).

pointer

Of course, it is common to use raw pointers instead of dynamic allocation, but dynamic allocation can replace pointers in most cases, so dynamic allocation should generally be preferred unless you have to use pointers.

1. The use of reference semantics. Sometimes you may need to pass a pointer to an object (regardless of how the object is allocated) so that you can access/modify the object's data (rather than a copy of it) in a function, but in most cases you should prefer to use references rather than pointers because references are designed to fulfill this requirement. Note that in this way, the object lifetime is still self-maintained within its scope. Of course, there is no need to use reference semantics if the requirements can be met by passing a copy of the object.

2. Use polymorphic cases. Polymorphic functions are called by passing pointers or references to objects (different handler functions are called depending on the input parameter type). If your design is such that you can pass pointers or references, obviously you should give preference to passing references.

3. In the case where the input parameter object is optional, it is common to pass a null pointer to indicate that the input parameter is ignored. If there is only one argument, preference should be given to default arguments or overloading the function. Otherwise, you should prioritize using a type that encapsulates this behavior, such as boost::optional or std::optional

4. Cases where compilation time is reduced by decoupling compilation type dependencies. One advantage of using pointers is that they can be used for forward declarations pointing to specific types (if object types are used, objects need to be defined), which can reduce the number of files involved in compilation and significantly improve compilation efficiency, as shown in the use of Pimpl idiom.

5. Interaction with C or C-style libraries. Only pointers can be used in this case, and in this case you want to make sure that pointer usage is limited to the necessary code segments. Pointers can be obtained by smart pointer transformations, such as using the get member function of smart pointers. If the memory allocated by the C library operation needs to be maintained in your code and explicitly released, you can encapsulate the pointer in a smart pointer and effectively release the object by implementing deleter.

About "C++ in the use of pointer object is what" the content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of the knowledge of "what is the reason for using pointer objects in C++". If you still want to learn more knowledge, please pay attention to the industry information channel.

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

Development

Wechat

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

12
Report