开发者

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());

? I.e., 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, e.g., 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜