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.)
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.)
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.delete[] to free arrays allocated with new[].delete memory you did not allocate with new (mixing malloc/free and new/delete is UB).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).
Jump to Post— mitrmkar 1,056If 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, …
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.
yes
[edit] damn, even with only 1 word to type, mitrmkar beat me to it
lol, thanks.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.