Question

Given the code below, what is the difference between unique_ptr and Bar that made bar ( { new int } ); ok but not foo( { new int } );

#include <memory>

struct Bar {
    Bar() = default;
    Bar( int* m ) : m_( m ) {};
    ~Bar() { if ( m_ ) delete m_; }
    explicit operator bool() const { return m_; }
private:
    int* m_ {};
};

bool bar( Bar && a ) { return bool(a); }
bool foo( std::unique_ptr<int> && a) { return bool(a); }

int main() {
    bar( { } );            // ok
    bar( Bar{ new int } ); // ok
    bar( { new int } );    // ok

    foo( { } );                             // ok
    foo( std::unique_ptr<int>{ new int } ); // ok
    foo( { new int } );                     // compile error
}

The compilation error with clang 3.5 :

+ clang++ -std=c++1y -O3 -W -Wall -Wextra -pedantic -pthread main.cpp
main.cpp:22:5: error: no matching function for call to 'foo'
foo( { new int } );                     // compile error
^~~
main.cpp:13:6: note: candidate function not viable: cannot convert initializer list argument to 'std::unique_ptr<int>'
bool foo( std::unique_ptr<int> && a) { return bool(a); }
Was it helpful?

Solution

The single-argument pointer constructor of unique_ptr is explicit:

explicit unique_ptr( pointer p );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top