首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >unique_ptr函数调用中带大括号初始化的自动类型推导失败

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

Stack Overflow用户
提问于 2014-01-28 12:33:33
回答 1查看 156关注 0票数 0

给出下面的代码,unique_ptr和Bar之间的区别是什么使bar ( { new int } );正常,而不是foo( { new int } );

代码语言:javascript
复制
#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的编译错误:

代码语言:javascript
复制
+ 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); }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-28 12:36:19

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

代码语言:javascript
复制
explicit unique_ptr( pointer p );
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21405646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档