In my code, I just noticed that I quite often need to check the nullptr value, although nullptr may not be possible (in accordance with the specified requirements).
However, nullptr can still happen, as other people can send nullptr, believing that this is normal (unfortunately, not every read / write specification), and this defect cannot be detected if the problem does not start at run time during testing time (and high test coverage is expensive). Thus, this can lead to numerous post-release errors reported by customers.
eg.
class data { virtual void foo() = 0; }; class data_a : public data { public: virtual void foo(){} }; class data_b : public data { public: virtual void foo(){} }; void foo(const std::shared_ptr<data>& data) { if(data == nullptr)
Usually I just used value types and passed by reference and copy. However, in some cases, I need a polymorphism that requires pointers or references.
So, I started using the following “compile-time polymorphism”.
class data_a { public: void foo(){} private: struct implementation; std::shared_ptr<implementation> impl_;
Does anyone else think this is a good idea when it is practical? Or am I missing something? Are there any potential problems with this practice?
EDIT:
"Problem" using links - you cannot move the ownership of the link (for example, return an object).
data& create_data() { data_a temp; return temp; }
The problem with rvalue links (does polymorphism work with rvalue links?), Then it becomes that you cannot share property.
data&& create_data() { return std::move(my_data_); }
A "safe" pointer based on shared_ptr sounds like a good idea, but I would still like to find a solution in which non-void will be enforced at compile time, maybe this is not possible.