c++ - Why is the class holding a reference copyable? -


having class holding reference expect following code fail miserable, compiles:

#include <iostream>  struct referenceholder {     std::string& str;      referenceholder(std::string& str)     :   str(str)     {} };  // why compile? referenceholder f() {     std::string str = "hello";     return referenceholder(str); }  int main() {     referenceholder h  = f();     std::cout << "should garbage: " << h.str << '\n';     return  0; } 

compiler: g++ 4.7.2 (with -std=c++11)

edit: -fno-elide-constructors compiles happily

there's no problem copy-initialising class, example does: new reference initialised refer same object old one. of course, undefined behaviour when function return leaves reference dangling.

the reference prevents default-initialisation , copy-assignment; following small change fail reasons:

referenceholder h;  // error: can't default-initialise reference h = f();            // error: can't reassign reference. 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -