c++ passing a string literal instead of a const std::string&?

前端 未结 3 681
旧时难觅i
旧时难觅i 2021-02-14 10:01

I have the following code which compiles with no warnings (-Wall -pedantic) with g++

#include 
#include 

using namespace std;

cla         


        
3条回答
  •  滥情空心
    2021-02-14 10:56

    The reason why this fails is because it essentially compiles to the following under the hood.

    Foo o(std::string("wurd"));
    

    In this case the Foo value is taking a reference to a temporary object which is deleted after the constructor completes. Hence it's holding onto a dead value. The second version works because it's holding a reference to a local which has a greater lifetime than the Foo instance.

    To fix this change the memebr from being a const std::string& to a const std::string.

提交回复
热议问题