
Hi all, I was trying to understand the use of boost::ref and boost::cref and wrote this little snippet: #include <iostream> #include <boost/ref.hpp> #include <string> using namespace std; int main(int argc,char** argv) { boost::reference_wrapper<string const> ref=boost::cref(string("yoh")); const string das("bla"); const string & dasref=das; cout<<"das ref is "<<dasref<<endl; cout<<"ref is "<<ref.get()<<endl; return 0; } I am confused by what I get when I run this: das ref is bla ref is bla I was expecting: das ref is bla ref is yoh What am I doing wrong there ??

roblin@jlab.org wrote:
Hi all, I was trying to understand the use of boost::ref and boost::cref and wrote this little snippet:
[...]
boost::reference_wrapper<string const> ref=boost::cref(string("yoh"));
The string( "yoh" ) temporary is destroyed at the ; and you reference_wrapper ends up dangling. A real reference string const & ref = string("yoh"); is special-cased by the language to prevent the destruction of the temporary string, but reference_wrapper cannot do so. You need to initialize it with a real object, not a temporary. string yoh( "yoh" ); boost::reference_wrapper<string const> ref = boost::cref( yoh );
participants (2)
-
Peter Dimov
-
roblin@jlab.org