Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++ standard guarantee that a failed insertion into an associative container will not modify the rvalue-reference argument?

#include <set> #include <string> #include <cassert>  using namespace std::literals;  int main() {     auto coll = std::set{ "hello"s };     auto s = "hello"s;     coll.insert(std::move(s));     assert("hello"s == s); // Always OK? } 

Does the C++ standard guarantee that a failed insertion into an associative container will not modify the rvalue-reference argument?

like image 265
xmllmx Avatar asked Aug 15 '19 15:08

xmllmx


1 Answers

Explicit and unequivocal NO. Standard doesn't have this guarantee, and this is why try_emplace exists.

See notes:

Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as std::map<std::string, std::unique_ptr<foo>>. In addition, try_emplace treats the key and the arguments to the mapped_type separately, unlike emplace, which requires the arguments to construct a value_type (that is, a std::pair)

like image 186
SergeyA Avatar answered Oct 13 '22 11:10

SergeyA