Are there any cases where it is incorrect to replace push_back with emplace_back?

前端 未结 6 1449
不思量自难忘°
不思量自难忘° 2021-01-02 09:44

Can I break a valid C++03 program by replacing std::vector::push_back with emplace_back and compiling it with C++ 11 compiler? From reading e

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 10:17

    Suppose a user-defined class could be initialized from braced-initializer. e.g.

    struct S {
        int value;
    };
    

    then

    std::vector v;
    
    v.push_back({0});    // fine
    v.emplace_back({0}); // template type deduction fails
    

    std::vector::emplace_back is template function but std::vector::push_back is non-template function. With a braced-initializer std::vector::emplace_back would fail because template argument deduction fails.

    Non-deduced contexts

    6) The parameter P, whose A is a braced-init-list, but P is not std::initializer_list or a reference to one:

    LIVE

提交回复
热议问题