Is inserting an element of a std::vector into the same vector allowed?

北城余情 提交于 2019-12-04 22:51:41

To answer the second question first: the standard explicitly says that the standard library is allowed to assume that when passing something by rvalue reference, that rvalue reference is the only reference to that object. This means that it cannot legally be an element of the vector. The relevant part of C++11 17.6.4.9/1:

  • If a function argument binds to an rvalue reference parameter, the implementation may assume that this parameter is a unique reference to this argument. ... [ Note: If a program casts an lvalue to an xvalue while passing that lvalue to a library function (e.g. by calling the function with the argument move(x)), the program is effectively asking that function to treat that lvalue as a temporary. The implementation is free to optimize away aliasing checks which might be needed if the argument was an lvalue. —end note ]

This leaves us just to handle the const T & case. And even though libstdc++ and libc++ differ in this case, their net result is the same—they will correctly copy from the object passed in. And the standard only prescribes behaviour, not implementation. As long as they achieve the correct behaviour, they're fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!