As the tile implies, in C++ we cannot have contains that hold references since objects inside containers have to be assignable. We cannot reassign a reference after it's been initialized.
However, in my program, I have a static const std::map
that holds const reference as values and it compiles fine. I am wondering if the reason is because the map is declared as const and initialized at declaration, which tells the compiler that "this object is const and its content will not change so it's ok to hold const reference as its values".
I couldn't find answers anywhere else. The code works but I don't want it to confuse other developers.
Edit, Sorry I didn't include the code. Here it goes:
const glm::dvec4& GetObjectColor(const msg::ObjectType type) {
static const std::map<msg::ObjectType, const glm::dvec4&> kObjectColorMap = {
{msg::ObjectType::PERSON, kWhite},
{msg::ObjectType::ANIMAL, kSilver},
{msg::ObjectType::SEDAN, kGray},
{msg::ObjectType::SUV, kRed},
{msg::ObjectType::VAN, kMaroon},
{msg::ObjectType::BICYCLE, kYellow},
{msg::ObjectType::TRICYCLE, kOlive},
{msg::ObjectType::MOTORCYCLE, kLime},
{msg::ObjectType::TRUCK, kGreen},
{msg::ObjectType::BUS, kAqua},
{msg::ObjectType::PICKUP, kTeal},
{msg::ObjectType::UNKNOWN, kBlue}};
return kObjectColorMap.at(type);
}