If you use the new operator on a class, say

class dummy { public: string f; };
int main(int argc, char *argv[]) {
  dummy *p = new dummy;
  return 0;
}

do you have to use the delete operator on p ? (since, apparently, it utilizes new.)

Dani AI

Generated

Short replies from and are fine; the following adds practical context and safer patterns you can apply today.

When an object is allocated on the free store, its destructor runs only when that object is destroyed — typically by delete or by an owning RAII wrapper. If you never destroy it, the destructor is not called and any resources the object holds (open handles, memory owned by members, etc.) can leak. The operating system will reclaim raw process memory at program exit, but it does not run C++ destructors for leaked objects, so relying on that is fragile and hides bugs.

Common pitfalls and quick rules:

  • delete on a null pointer is safe; double delete is undefined behavior.
  • Use delete[] to free arrays allocated with new[].
  • Do not delete memory you did not allocate with new (mixing malloc/free and new/delete is UB).
  • Use tools like AddressSanitizer, Valgrind, or your compiler/CRT debug modes to find leaks.

Prefer RAII instead of naked new/delete. Example (modern C++):

#include <memory>

struct MyClass { /* ... */ };

int main() {
  auto p = std::make_unique<MyClass>(); // no explicit delete; destructor runs when p is destroyed
}

For single ownership use std::unique_ptr, for shared ownership std::shared_ptr, or avoid dynamic allocation entirely when possible. See the std::unique_ptr reference for details: (https://en.cppreference.com/w/cpp/memory/unique_ptr) and the language new page for what allocation/destruction entail: (https://en.cppreference.com/w/cpp/language/new).

Recommended Answers

All 3 Replies

If you use the new operator on a class, say

class dummy { public: string f; };
int main(int argc, char *argv[]) {
  dummy *p = new dummy;
  return 0;
}

do you have to use the delete operator on p ? (since, apparently, it utilizes new.)

Yes, when you want to release that memory, 'delete' needs to be issued.

commented: Yes indeed +17

yes

[edit] damn, even with only 1 word to type, mitrmkar beat me to it

commented: You shouldn't have wasted your time spell checking it then ;) +17

lol, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.