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

前端 未结 5 1099
独厮守ぢ
独厮守ぢ 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:43

    Because your temporary string went out of scope once the Sandbox constructor returned, and the stack occupied by it was reclaimed for some other purposes.

    Generally, you should never retain references long-term. References are good for arguments or local variables, never class members.

提交回复
热议问题