Rvalue as lvalue

Found workaround how to use rvalue as lvalue :

&(std::string()=std::string("Hello World"));

but not sure is it legal to use this construction.

Code same to this is working for me

typedef std::pair<const char *, const std::string *> custom_pair;

std::ostream & operator <<(std::ostream & os, const custom_pair & kv)
{
    if (kv.first && kv.second && !kv.second->empty())
      os << kv.first << *kv.second;

    return os;
  }

std::ostringstream q;
q << custom_pair("example_string=", &(std::string() = IntToString(1)));

where custom_pair constructor needs address as second parameter, but can someone explain is it correct to use this?

Upvotes: 3

Views: 260

Answers (3)

R Sahu
R Sahu

Reputation: 206667

but not sure is it legal to use this construction.

You are on the border of running into UB.

std::ostringstream q;
q << custom_pair("example_string=", &(std::string() = IntToString(1)));

works ok since all the temporary objects are still alive when the pointer is dereferenced. Change that to:

std::ostringstream q;
custom_pair p("example_string=", &(std::string() = IntToString(1)));
q << p;

and you are suddenly in UB territory.

Upvotes: 2

Ludwig Schulze
Ludwig Schulze

Reputation: 2325

It's ok in your use case. The temporary object is destroyed at the semicolon after the "<<" operation. By then, it is no longer in use.

Be careful not to use this pattern when the pointer might still be used after the temporary is destroyed.

That said, I would not accept this code in a code review. Everyone reading this would have too much trouble to determine why it works. As you can see by the comments below your question.

Upvotes: 2

Slava
Slava

Reputation: 44268

Found workaround how to use rvalue as lvalue

You do not need workaround on how to use rvalue as lvalue, but rather fix your code that you do not need this workaround. For example second type of the pair should be std::string, not const std::string * and all your problems would go away.

Upvotes: 0

Related Questions