Strange behavior with emplace_back and push_back

Here is the code:

#include <string> #include <vector> #include <iostream> #include <sstream> #include <iomanip> class Date { public: Date(int year, int month, int day) : year(year), month(month), day(day) {} Date(const Date &d) : year(d.year), month(d.month), day(d.day) {} std::string to_string() { std::stringstream ss; ss << std::setfill('0') << std::setw(4) << year << '-' << std::setw(2) << month << '-' << day; return ss.str(); } private: int year, month, day; }; int main() { std::vector<Date> vd; vd.emplace_back(2017, 1, 13); vd.emplace_back(vd[0]); std::cout << vd.back().to_string() << "\n"; } 

When I compile and run it using VS2015 (compiler 19.00.24215.1), it prints nonsense like 20750440-20709568-13 . When I compiled it with g ++ 4.8.4, it prints 2017-01-13 , as expected. However, if I replace vd.emplace_back(vd[0]) with vd.push_back(Date(vd[0])) , it prints 2017-01-13 with both VS2015 and g ++.

I previously suggested that vector::emplace_back(args) functionally equivalent to vector::push_back(Ctor(args)) , possibly avoiding a copy? Why do they produce different behavior here? Is this a VS2015 error?

+5
source share

Source: https://habr.com/ru/post/1262763/


All Articles