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

前端 未结 3 711
旧时难觅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:41

    Whats happening is that the reference 'str' is being initialized so that it points to the temporary arg, 's'. Its pretty much the same as using a pointer - you're counting on the continued existence of your constructor arg, 's'. When the temporary is deleted (after the constructor ftn returns), then your reference now points at garbage.

    To fix, change str so that its an actual string object and not a reference.

    const std::string str;

    That way a copy will be made of your arg string, and said copy will have the same lifespan as your Foo object.

提交回复
热议问题