使用unique_ptr在函数调用中使用大括号初始化自动类型推导失败

时间:2014-01-28 12:33:33

标签: c++ c++11 unique-ptr list-initialization

根据下面的代码,unique_ptr和Bar之间的区别是bar ( { new int } );好,但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
}

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

1 个答案:

答案 0 :(得分:7)

unique_ptr的单参数指针构造函数是explicit

explicit unique_ptr( pointer p );