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

前端 未结 6 1470
不思量自难忘°
不思量自难忘° 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:11

    I constructed a short example that actually fails to compile when push_back is replaced by emplace_back:

    #include 
    struct S {
        S(double) {}
      private:
        explicit S(int) {}
    };
    int main() {
        std::vector().push_back(0); // OK
        std::vector().emplace_back(0); // error!
    }
    

    The call to push_back needs to convert its argument 0 from type int to type S. Since this is an implicit conversion, the explicit constructor S::S(int) is not considered, and S::S(double) is called. On the other hand, emplace_back performs direct initialization, so both S::S(double) and S::S(int) are considered. The latter is a better match, but it's private, so the program is ill-formed.

提交回复
热议问题