std::unique_ptr usage

后端 未结 3 725
后悔当初
后悔当初 2021-02-01 14:08
std::unique_ptr p1(new int);
std::unique_ptr p2(new int);
p2=p1;

It seems here that p1 is no longer \"unique\" since p2 refer to

3条回答
  •  盖世英雄少女心
    2021-02-01 14:17

    Here is an article I wrote which answers your questions. I originally wrote this article to present an emulation of unique_ptr. However you can ignore the first few paragraphs dealing with the emulation and just start reading at "Basic Examples".

    http://howardhinnant.github.io/unique_ptr03.html

    Edit:

    I had trouble distilling the above linked article down to something small enough to make a practical answer in this format. However here is my best shot:

    The reason: Safety in generic code. One can not really make copies of either auto_ptr or unique_ptr. Consider:

    template 
    void foo(T t)
    {
        T copy_of_t = t;  // line 4
        assert(copy_of_t == t);
    }
    

    It is not unusual at all for generic code to look like foo above. The assert is probably not actually there, but the assumption that the assert would hold often is there ... implicitly. Indeed, a popular implementation of std::sort had exactly this logic in 1996, which is exactly what prompted the second auto_ptr redesign (which helped, but didn't completely fix the problem).

提交回复
热议问题