Lets say I have a struct as value
struct Friend { Person * a, Person* b}
Then I have another class as key
class Relation;
Now I want to create a key value relation
std::unordere_map<Relation*, Friend> my_map;
I have tried
Relation* r;
Person * p1;
Person * p2;
my_map[r] = {p1, p2}; // works
my_map[r] = new Friend(p1,p2); // does not work
// error says : error: no match for 'operator='
// my_map[r] = Friend(p1, p2); /// also does not work
// After Edit from Zan
// error: no matching function for call to 'Friend::Friend()'
struct Friend {
Friend(Person* x, Person* y){
a = x;
b = y;
}
Person * a;
Person* b;
}
Friend, notFriend*(ie: not a pointer). Thereforemy_map[r] = new Friend(p1,p2);won't work, as you're trying to store a pointer as the valuestd::unordered_map<Relation*, Friend*> my_map;std::unique_ptr. If you want to store a non-owning pointer, then raw pointers are fine. In c++11 and later, seeingnewin your code is considered a code-smellRelation *rbut never set it to anything. It will have the value of whatever was in the stack or register before, which is bad. On some compilers and architectures trying to use that unset pointer might even crash your program (Itanium not-a-thing marking, for one). Which is much better than wondering why your program sometimes works or doesn't, depending on the values passed to some previous function.