Live data from Hacker News

Curious Pointers of Modern C++

blog.digitalreverie.com

1–2 of 2 posts

Re: Curious Pointers of Modern C++

#2
First i must correct terminology: The OP got the terms "upcast" and "downcast" the wrong way around. Assigning something to a more general variable is an upcast, rediscovering something derived needs a downcast. Upcasts are absolutely fundamental and always automatic in object oriented languages, downcast are possible at least in C++, but considered as bad style.

MAKE_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.