Why does unique_ptr overload reset(pointer p = pointer()) and reset(nullptr_t)?

放肆的年华 提交于 2019-12-01 08:42:10

The

template< class U > 
void reset( U ) = delete;

would be chosen for a call with nullptr argument, if not for

void reset( std::nullptr_t p );

That's why it exists, to allow the call with nullptr.


Example (compile with FIX defined to suppress the compilation error):

#include <cstddef>      // std::nullptr_t

struct S
{
    void reset( char* ) {}

    template< class Type >
    void reset( Type ) = delete;

    #if FIX
    void reset( std::nullptr_t ) {}
    #endif
};

auto main() -> int
{
    S().reset( nullptr );    // Fails when FIX is not defined.
}

reset ist implemented as

pointer old = this->ptr;
this->ptr= newPointer;
delete[] old;

The templated overload is deleted for arrays to prevent the following case

class foo{};
class bar : public foo {};

foo* managedPointer = new foo[3];
bar* newPointer = new bar[5];

foo* old = managedPointer;
managedPointer = newPointer;
delete[] old;

Which is undefined behavior. Section 5.3.5 paragraph 3:

[...] In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

Since deleted functions still participate in overload resolution and reset(U) provide a better match for nullptr than reset(pointer) , there is an additional overload to to allow reset(nullptr), which would otherwise give a compiler error and thus result in an inconsistent interface between array and pointer version.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!