右值作为左值

Rvalue as lvalue

本文关键字:      更新时间:2023-10-16

找到了如何使用右值作为左值的解决方法:

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

但不确定使用这种结构是否合法。

与此相同的代码对我有用

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)));

构造函数需要地址作为第二个参数custom_pair但有人可以解释使用它是否正确吗?

在您的用例中没问题。临时对象在"<<"操作后在分号处销毁。到那时,它已不再使用。

当指针在销毁临时指针后可能仍可用时,请注意不要使用此模式。

也就是说,我不会在代码审查中接受此代码。每个阅读本文的人都很难确定它为什么有效。正如您在问题下方的评论中看到的那样。

但不确定使用这种结构是否合法。

你正处于遇到UB的边缘。

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

工作正常,因为当指针被取消引用时,所有临时对象都仍然处于活动状态。将其更改为:

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

你突然进入了UB的领地。

找到了如何将右值用作左值的解决方法

您不需要有关如何使用 rvalue 作为左值的解决方法,而是修复您不需要此解决方法的代码。例如,第二种类型的配对应该是std::string,而不是const std::string *,你所有的问题都会消失。

相关文章:
  • 没有找到相关文章