给出下面的代码,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); }发布于 2014-01-28 12:36:19
unique_ptr的单参数指针构造函数是explicit。
explicit unique_ptr( pointer p );https://stackoverflow.com/questions/21405646
复制相似问题