Does a const reference class member prolong the life of a temporary?

前端 未结 5 1093
独厮守ぢ
独厮守ぢ 2020-11-21 08:04

Why does this:

#include 
#include 
using namespace std;

class Sandbox
{
public:
    Sandbox(const string& n) : member(n) {         


        
5条回答
  •  爱一瞬间的悲伤
    2020-11-21 08:57

    you're referring to something which has vanished. The following will work

    #include 
    #include 
    
    class Sandbox
    {
    
    public:
        const string member = " "; //default to whatever is the requirement
        Sandbox(const string& n) : member(n) {}//a copy is made
    
    };
    
    int main()
    {
        Sandbox sandbox(string("four"));
        std::cout << "The answer is: " << sandbox.member << std::endl;
        return 0;
    }
    

提交回复
热议问题