0

Currently (since C++11) it is simple to design boost::recursive_wrapper using std::unique_ptr:

template< typename T >
class recursive_wrapper
{

    std::unique_ptr< T > storage;

public :

    template< typename ...Args >
    recursive_wrapper(Args &&... args)
        : storage(std::make_unique< T >(std::forward< Args >(args)...))
    { ; }

    template< typename R >
    operator R & () noexcept
    {
        return static_cast< R & >(*storage);
    }

    template< typename R >
    operator R const & () const noexcept
    {
        return static_cast< R const & >(*storage);
    }

    void
    swap(recursive_wrapper & other) noexcept
    {
        storage.swap(other.storage);
    }

};

But currently it designed via operator ::new and boost::checked_delete. It is considered a bad practice to use raw new and delete operators in modern C++.

If target is only C++11 and newer, are there any downsides to implement recursive_wrapper using std::unique_ptr as it is above (I mean both compile-time performance and run-time performance degradation for example or maybe something else)? What if backward compatibility as a requirement ceased to exist?

Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169

1 Answers1

1

I think you'll find that the reason not to do this has nothing to do with performance.

boost::recursive_wrapper was specifically designed to allow boost::variants to contain themselves. I'm pretty sure that if you check the implementation of boost::variant you'll find that template expansion of a recursive template relies on specialisations that look something like this:

template<class...T> 
struct SomeClass<boost::recursive_wrapper<boost::variant<T...>>> 
{
    ....

Which, unless you are planning to re-implement boost::variant to use a different wrapper class, would make them incompatible.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • I am not planning to use custom implementation of `recursive_wrapper` for namely `boost::variant`, but for [another implementation of variant](https://github.com/mapbox/variant). There no such an issue for that implementation. Are there any other downsides imaginable? – Tomilov Anatoliy Feb 02 '16 at 09:50
  • @Orient no, I don't think so. You'll have to remember to custom-code the copy constructor and copy operator *if* T supports those operations. – Richard Hodges Feb 02 '16 at 09:58
  • `T` is incomplete if I use it to define recursive structures, so type traits are not well-formed for `recursive_wrapper< T >` at point of its instantiation. [There is workaround](https://github.com/tomilov/variant/blob/master/include/versatile/recursive_wrapper.hpp#L31), I know it and I use it. – Tomilov Anatoliy Feb 02 '16 at 10:17