简体   繁体   中英

C++11 Pointer Uniquify Helper Function

In C++11, I'm missing a syntatic sugar for uniquifying a pointer into std::unique_ptr . I therefore wrote the following litte helper function std::uniquify_ptr typically used to easy (non-constructor) assignment of mutable class members (typically different kinds of caches ).

#include <memory>

namespace std
{
    template<typename T>
    inline unique_ptr<T> uniquify_ptr(T* ptr)
    {
        return unique_ptr<T>(ptr);
    }
}

Am I missing something from a safety point of view here? Is some similar function already available?

No, there is no similar function already available. How is

auto ptr(std::uniquify_ptr(new T()));

any better than

std::unique_ptr<T> ptr(new T());

? Ie, why should this exist? It's not saving you much if anything.

unique_ptr<T> can already directly construct from a T* , so there's little need. Such a factory function has little use except for syntactic sugar, eg, auto x = make_unique<T>(...); . Also, your move is redundant.

@Schaub: I'm using this to change the value of an existing mutable std::unique_ptr class member. In that case

m_hashA = std::uniquify(new Hashes(cnt));

is more convenient than

m_hashA = std::unique_ptr<Hashes>(new Hashes(cnt)));

vere the member is declared as

mutable std::unique_ptr<Hashes> m_hashA; ///< Hash Table for Alternatives.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM