0

Since rvalue references were not supported before C++11, there were no move constructors. The const T& arguments makes it use the copy constructor even for temporaries, which is the same as calling the copy constructor via a by-value argument? std::vector's void push_back(const T& Val) allows Val to receive the right value, so why not pass it by value?

The other question is: Why can const T& receive right values?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • I tried to rephrase the question as-best I understood it. I hope I didn't destroy it for you. – Ted Lyngmo Aug 23 '23 at 11:27
  • And if I understand it correctly, taking it by value would imply always making _two_ copies instead of one. – Ted Lyngmo Aug 23 '23 at 11:28
  • 'when template T is int' vector::push_back(const int& num){//befror c++11, call copy constructor, assign 1 to num(is that right?) ...//after c++11, call move constructor make it cost less } vector::push_back(int num){//call by value ... } vector v; v.push_back(1);// is assignment via copy constructor the same cost as call by value? if it's same, why not use the second way? – hhu_clj Aug 24 '23 at 02:28
  • I understand, thanks for your answer. if it's call by value, first call copy constructor :assign 1 to num, then second call copy constructor :Constructs the parameter copy to the tail of the data container ; if call by reference it will just call one time copy constructor to assign 1 to num. – hhu_clj Aug 24 '23 at 02:51
  • When you have fundamental types it would probably be better to take them by value but it also need to work well with bigger user- or implementation-defined types, like `std::string`. – Ted Lyngmo Aug 24 '23 at 06:03

0 Answers0