Clarifying a Common Source of Pointer Confusion

Clarifying a Common Source of Pointer Confusion

Novices, especially those who have experience with garbage-collected languages, are often confused with the concept of object deallocation and destruction in C++. They tend to explicitly invoke every object’s destructor or assume that every pointer must be deleted explicitly. However, in C++, there is a simple rule: only objects that were allocated by new must be destroyed using delete. When dealing with arrays allocated by new[], you must use delete[]. When shouldn’t you use delete? First of all, when you have local automatic objects and static objects. These objects are destroyed automatically. Never attempt to destroy them explicitly. Furthermore, even if you have a pointer that is later assigned to an object, you shouldn’t delete this pointer if its bound object wasn’t allocated using new. Here’s an example:

 void f(){ string s; // local automatic object string *ps; ps = &s; // assign address of s to ps}

Because s is a local automatic object, you shouldn’t delete the pointer ps. The bound object s will be destroyed automatically when f() exits. Remember that deleting any object that wasn’t allocated using new causes undefined behavior (most likely?a program crash).

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes