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

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

    Technically speaking, this program isn't required to actually output anything to standard output (which is a buffered stream to begin with).

    • The cout << "The answer is: " bit will emit "The answer is: " into the buffer of stdout.

    • Then the << sandbox.member bit will supply the dangling reference into operator << (ostream &, const std::string &), which invokes undefined behavior.

    Because of this, nothing is guaranteed to happen. The program may work seemingly fine or may crash without even flushing stdout -- meaning the text "The answer is: " would not get to appear on your screen.

提交回复
热议问题