I would like to use a std::map
(or prob. std::unordered_map
) where i insert custom object keys and double values, e.g. std::map<CustomClass,double>
.
The order of the objects does not matter, just the (fast) lookup is important. My idea is to insert the address/pointer of the object instead as that has already have a comparator defined, i.e. std::map<CustomClass*,double>
In Pointers as keys in map C++ STL it has been answered that this can be done but i am still a bit worried that there might be side effects that are hard to catch later.
Specifically: Can the address of an object change during runtime of the program? And could this lead to undefined behavior for my lookup in the map?
A test program could be:
auto a = adlib::SymPrimitive();
auto b = adlib::SymPrimitive();
auto c = adlib::mul(a,b);
auto d = adlib::add(c,a);
// adlib::Assignment holds std::map which assigns values to a,b
auto assignment = adlib::Assignment({&a,&b},{4,2});
// a=4, b=2 -> c=8 -> d=12
adlib::assertEqual(d.eval_fcn(assignment), 12);
which is user code, so users could potentially put the variables into a vector etc.
Update:
The answers let me think about users potentially inserting SymPrimitives
into a vector, a simple scenario would be:
std::vector<adlib::SymPrimitive> syms{a,b};
auto assignment = adlib::Assignment({&syms[0],&syms[1]},{4,2}); // not allowed
The pitfall here is that syms[0]
is a copy of a
and has a different address. To be aware of that i could probably make the responsibility of the user.