In C++, is it OK to steal resources from a map that I do not need afterwards anymore? More precisely, assume I have a std::map
with std::string
keys and I want to construct a vector out of it by stealing the resources of the map
s keys using std::move
. Note that such a write access to the keys corrupts the internal datastructure (ordering of keys) of the map
but I won't use it afterwards.
Question: Can I do this without any problems or will this lead to unexpected bugs for example in the destructor of the map
because I accessed it in a way that std::map
was not intended for?
Here is an example program:
#include<map>
#include<string>
#include<vector>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
std::vector<std::pair<std::string,double>> v;
{ // new scope to make clear that m is not needed
// after the resources were stolen
std::map<std::string,double> m;
m["aLongString"]=1.0;
m["anotherLongString"]=2.0;
//
// now steal resources
for (auto &p : m) {
// according to my IDE, p has type
// std::pair<const class std::__cxx11::basic_string<char>, double>&
cout<<"key before stealing: "<<p.first<<endl;
v.emplace_back(make_pair(std::move(const_cast<string&>(p.first)),p.second));
cout<<"key after stealing: "<<p.first<<endl;
}
}
// now use v
return 0;
}
It produces the output:
key before stealing: aLongString
key after stealing:
key before stealing: anotherLongString
key after stealing:
EDIT: I would like to do this for the entire content of a large map and save dynamic allocations by this resource stealing.
const
value is always UB. – Iloilovector
from a function and I need the temporarymap
for the construction. – Neophytestd::string
has short-string optimization. Meaning that there is some non-trivial logic on copying and moving and not just pointer exchange and in addition most of the time moving implies copying - lest you deal with rather long strings. The statistical difference was small anyways and in general it surely varies depending on what kind of string processing is performed. – Marjorie