I learned some basic C in school, and continued using C for a while.
If I wanted to create something on the heap, I used malloc()
and free()
for it.
After some time passed, I started using some C and work with objects. I was told that I should not use malloc()
and free()
in C , but rather new
and delete
, which made sense to me because I now could use custom constructors for my objects when creating them on the heap.
Now I read that you should try to avoid raw pointers as much as possible, and rather try to use smart pointers. In my case, I only need the object at one place, but declare it at the start of my program and do not have to copy it somewhere, so I guess I should use std::unique_ptr
?
A* a1 = nullptr;
a1 = (A*)malloc(sizeof(A)); // cant call constructor
// Do stuff
free(a1);
A* a2 = nullptr;
a2 = new A(2);
// Do stuff
delete a2;
std::unique_ptr<A> a3 = nullptr;
a3 = std::unique_ptr<A>(new A(3));
// Do stuff
// No need to delete
std::unique_ptr<A> a4 = nullptr;
a4 = std::make_unique<A>(4);
// Do stuff
// No need to delete
I came up with these methods to create a pointer to my object.
a1
is useless for me because I can not call a constructora2
is apparently bad because I have to manually manage the memory?
So I thought I should use either a3
or a4
, but I am still left with some questions.
Did I get it right that I do not need to delete anything with either of those two variants, and that the class destructor will be called when the std::unique_ptr
goes out of scope? Are there other options? And which would be the best choice?
CodePudding user response:
a1
is useless for me because I can not call a constructor
You can, using placement-new if I am not mistaken:
new (a1) A();
Did I get it right that I do not need to delete anything with either of those two variants, and that the class destructor will be called when the
std::unique_ptr
goes out of scope?
Yes.
And which would be the best choice?
You would just use:
auto a4 = std::make_unique<A>(4);