c++ - Why my const ref becomes invalid? -


why const ref becomes invalid in code , how avoid this? can't copy, bottleneck in application.

class foo { public:     const std::string& string() const {         return string;     }  private:     std::string string = "asdf"; };  foo foo; std::vector<std::pair<const std::string&, int>> invalid; (int = 0; < 5; i++) {     invalid.emplace_back(std::make_pair(foo.string(), i);     // after line invalid[i].first invalid } 

igor tandetnik pointed out problem in code. fwiw, don't think it's idea have containers referencing other objects' members reference in case - there's implicit dependence on relative liftime of objects. can consider using shared_ptr const string, in following:

#include <string> #include <memory> #include <vector>                                                                                                                            class foo { public:     const std::shared_ptr<const std::string> string() const {         return _string;     }     private:     std::shared_ptr<std::string> _string = std::make_shared<std::string>("asdf"); };    int main() {        foo foo;     std::vector<std::pair<std::shared_ptr<const std::string>, int>> invalid;     (int = 0; < 5; i++) {         invalid.emplace_back(std::make_pair(foo.string(), i));     }    }    

Comments