In C++, I have two block of codes like this:
Base *base = new Base();
base->showName();
And:
Base base;
base.showName();
I don’t know when do we use pointer and when not? And what’s different and what is better?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first code you showed is a memory leak.
The second snippet is Java, not C++.The question has been edited to use my suggested code.Generally though, in C++ you should avoid
newunless you really NEED dynamic lifetime. Instead, write:This is better because
If the object needs to live past the end of the scope, you should be using:
Now
unique_ptrwill free the memory for you when theunique_ptrdies, and it’s also exception-safe. When you return aunique_ptr, ownership is transferred to the caller, and he can reap the benefits of automatic cleanup.