Is it possible to write a smart pointer which allocates the object itself in its constructor - instead of the developer having to call new
? In other words, instead of writing:
std::unique_ptr<myClass> my_ptr(new myClass(arg1, arg2))
...one could write:
std::smarter_ptr<myClass> my_ptr(arg1, arg2)
Is the language syntax capable of expressing this? Would this be desirable? Hideous? I'm thinking in particular of protecting against this mistake (which I've made myself, of course):
myFunction(std::unique_ptr<myClass>(new myClass()), std::unique_ptr<myClass>(new myClass()))
...which risks leaking whichever object is allocated first if the second allocation happens and throws before the first object is safely ensconced in its smart pointer. But would a smarter pointer actually make this safe?
A smart pointer is like a regular (typed) pointer, like "char*", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using "->", but not if you need an actual pointer to the data. For that, you can use "&*ptr".
A std::weak_ptr helps to break the cycles of std::shared_ptr (R. 24). These cycles are the reason, a std::shared_ptr will not automatically release its resource.
Declare the smart pointer as an automatic (local) variable. (Do not use the new or malloc expression on the smart pointer itself.) In the type parameter, specify the pointed-to type of the encapsulated pointer. Pass a raw pointer to a new-ed object in the smart pointer constructor.
Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can’t like automatic destruction (yes, we don’t have to explicitly use delete), reference counting and more.
Why is smart pointer better? Smart pointers have one crucial advantage over raw pointers: they guarantee that their destructors are called during stack unwinding. That means that any memory allocated in constructors will be automatically freed. Let’s look at sample code, that illustrates the advantage of smart pointers over raw pointers.
Access the encapsulated pointer by using the familiar pointer operators, -> and *, which the smart pointer class overloads to return the encapsulated raw pointer. The C++ smart pointer idiom resembles object creation in languages such as C#: you create the object and then let the system take care of deleting it at the correct time.
Look at the implementation of make_shared()
. It does this allocates a new object and creates a shared_ptr
out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With