Declare a reference and initialize later?

后端 未结 10 2161
遥遥无期
遥遥无期 2020-12-01 05:58

I have a reference to MyOjbect, but the the exact object depends on a condition. So I want to do something like this:

MyObject& ref; 
if([co         


        
10条回答
  •  余生分开走
    2020-12-01 06:40

    What I like to do is a lambda that's immediately executed.

    Let's suppose we want a const std::string& to a variable from under the map - if map does not contain given key - we want to throw.

    int main()
    {
      std::map myMap = {{"key", "value"}};
    
      const std::string& strRef = [&]()->const std::string& {
        try {
          return myMap.at("key"); // map::at might throw out_of_range
        }
        catch (...) {
          // handle it somehow and/or rethrow.
        }
      }(); // <- here we immediately call just created lambda.
    }
    

    You could also use std::invoke() to make it more readable (since C++17)

    int main()
    {
      std::map myMap = {{"key", "value"}};
    
      const std::string& strRef = std::invoke([&]()->const std::string& {
        try {
          return myMap.at("key"); // map::at might throw out_of_range
        }
        catch (...) {
          // handle it somehow and/or rethrow.
        }
      });
    }
    

提交回复
热议问题