Curious Pointers of Modern C++
blog.digitalreverie.com
Curious Pointers of Modern C++
1–2 of 2 posts
Re: Curious Pointers of Modern C++
#2MAKE_UNIQUE & MAKE_SHARED
The first problem discussed stems from a misunderstanding of the function make_unique(https://en.cppreference.com/w/cpp/memory/unique_ptr/make_uni...), which produces always an unique_pointer owning an object of type T, no matter what. Part of the story is, that the class "Animal", has an defaulted copy constructor, this allows implicit conversion, which is considered as bad style. To mitigate i would suggest, to use the keyword "explicit" whenever possible, I have learned that it helps to prevent many, many surprises.
CAST TO A REFERENCE
This example program terminates surprisingly due to an unhandled "std::runtime_error" exception thrown from the Dog::breed() method. The reason is, that the auto type specifier uses function template type deduction rules, therefore in this case
const Animal& animal
...
auto dog = dynamic_cast(animal);
the variable "dog" is deduced to have the type "Dog". This again happens unnoticed, since the class "Animal" implicitely copy constructs from derived classes.TRICKY SHARED_PTR LAMBDA
A smart_ptr manages two(!) pointers of possibly different type and value, the "managed" pointer, which is shared by all instances and an additional "owned" pointer, private to every object instance. The owned pointer can be manipulated privately with the reset() method and will be referenced by the -> operator. Hence the difference in behaviour if a copy or a reference of the original shared pointer is made.