Hacker News new | ask | show | jobs
by SeanCline 3312 days ago
The idea of a value_ptr is something that's been around in C++ for quite some time, now. It usually goes by the name clone_ptr or copy_ptr. (Googling for either will yield several implementations.)

Looking at the author's code on GitHub, this implementation seems decent.

One thing to note about this implementation is that it doesn't address the other big reason for doing dynamic allocations: polymorphic types. Value semantics are preserved so faithfully that objects are sliced just as they would be if they weren't dynamically allocated.

Consider this example: https://gist.github.com/SeanCline/c81218e4c0208ccb871268aecd...

1 comments

For similar reasons it seems inappropriate for PIMPL. The template indirectly calls `sizeof(...)` on the template type. When that type is not concrete (which is likely the case with PIMPL) the code will not compile. The `value_ptr_example_pimpl.hpp` example doesn't compile for me using GCC 5.4.
Well, that isn't a flaw in the implementation of value_ptr. The example, as provided, won't compile because the the copy constructor, assignment operator, and destructor are declared `= default` in the header. This causes any translation units that include value_ptr_example_pimpl.hpp to attempt to stamp out the default implementation, which does require knowing `sizeof(Foo::Pimpl)`.

Moving those methods to value_ptr_example_pimpl.cpp, just as you'd normally do for PIMPL makes the compiler happy.

This works for me in VS2017 but should work on any C++11 compliant compiler: https://gist.github.com/SeanCline/55d700d4fbf8cc1bdaeb44b547...