devxlogo

New and Delete

Question:
In my class declaration I have a member:

CSomeUsefulClass* m_one;

In my implementation file, there is a function:

DoMyThing(){CSomeUsefulClass* m_two;m_two = new CSomeUsefulClass(param1, param2);//blah...m_one = m_two;//do my thing...}

then in the destructor of my class:

if(m_one)  delete m_one; 

Will this program cause a memory leak?

Answer:
No, your code won’t cause a memory leak because your destructor deletes the dynamically allocated object. However, I’m wary about the design. First of all, the object is allocated only when DoMyThing() is called. Are you sure it’s alyways called? And if so, what happens if you call it more than once? If the pointer already points to an object, you’re causing a memory leak. Finally, using two pointers that point to the same object is very dangerous.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.