I have a code snippet that uses std::map::emplace to insert elements into a map. The key is an internal version of a unique_ptr.
The standard states:
The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately.
In the following snippet, if the wrapper is constructed/destructed, it will correctly take destroy the naked pointer. If it is not, the object will be leaked. The snippet is just an example.
class Wrapper {
public:
Wrapper(int* param):
value(param) {}
~Wrapper() { delete value;}
bool operator<(const Wrapper& other) const { return *value < *other.value;}
private:
int * value;
};
int main()
{
std::map<Wrapper, int> map;
{
int *key = new int(100);
map.emplace(key, 5);
}
{
int *keyDuplicate = new int(100);
map.emplace(keyDuplicate, 10);
}
}
The handling seems to be implementation dependant. I could check the return value and destroy the object if it was a duplicate. But if the object was constructed and deleted, I would be deleting the pointer twice.