-1

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);  
}
Tao Chen
  • 51
  • 5

1 Answers1

0

No. You cannot.

Maybe you have seen this question already: Why does storing references (not pointers) in containers in C++ not work?

The premise of the quesiton is correct. You cannot store reference in containers.

... and it compiles fine.

Code not causing a compiler error cannot safely assumed to be correct. Actually "compiles without errors" is the lowest bar you can put on code. Consider this horribibly broken code:

int* dont_do_this_at_home;   
*dont_do_this_at_home = 42;   // serisouly: DONT DO THIS

No compiler I know will issue an error or warning for this code irrespective of the fact that this code could not be more broken. The best that can happen here is that you get a segmentation fault. The worst: Demons fly out of your nose. Read here about undefined behavior: https://en.cppreference.com/w/cpp/language/ub

As explained in the above linked Q&A, the language specs say: you cannot store reference in containers. If you still do it and your compiler will not generate an error, then you should not assume that you found a way around the rule.

It is similar to not being allow to toucht the ball with your hands in soccer. You can touch the ball with your hands, but that does not disprove the rule.

Consider this:

int a = 5;
std::map<int,int&> x{ { 1,a} };   // WRONG !!!

No compiler error, but still it is wrong. C++ isnt soccer, if you break the rules there is no referee that will tell you about it.

PS: there is std::reference_wrapper to store references in containers.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185