C++ C++;-如何通过引用返回prvalue?

C++ C++;-如何通过引用返回prvalue?,c++,c++11,rvalue,C++,C++11,Rvalue,因此,我正在实现一个本机数组包装器,它将允许这样的数组作为函数参数传递并返回。但是,我在将其强制转换到本机数组时遇到了问题,因为本机数组无法返回。作为替代,我决定使用强制转换运算符的“rvalue”引用返回类型,但这不会正确操作,因为如果我想将返回的对象绑定到“rvalue”引用中以延长其生命周期,这不会发生,因为它是“xvalue”而不是“prvalue”。这个问题有什么解决办法吗?也许是一些“prvalue”演员?或者是否有其他方法实现对“数组”的隐式转换 班级: template<t

因此,我正在实现一个本机数组包装器,它将允许这样的数组作为函数参数传递并返回。但是,我在将其强制转换到本机数组时遇到了问题,因为本机数组无法返回。作为替代,我决定使用强制转换运算符的“rvalue”引用返回类型,但这不会正确操作,因为如果我想将返回的对象绑定到“rvalue”引用中以延长其生命周期,这不会发生,因为它是“xvalue”而不是“prvalue”。这个问题有什么解决办法吗?也许是一些“prvalue”演员?或者是否有其他方法实现对“数组”的隐式转换

班级:

template<typename type>
struct tmp
{
    tmp() {}
    tmp(const tmp &) = default;
    tmp(const type & arg) : tmp(*(const tmp*)arg) {}

    && operator type() && {return static_cast<type&&>(d);}

    ~tmp () { cout << "tmp destructor" << endl; }

    type d;

};
模板
结构tmp
{
tmp(){}
tmp(const tmp&)=默认值;
tmp(consttype&arg):tmp(*(consttmp*)arg){}
&&运算符类型()&{return static_cast(d);}

~tmp(){coutprvalue是一个不是xvalue的右值,也称为“临时对象或其子对象,或与对象无关的值。”

您不能创建一个作为
临时对象(12.2)
的数组,也不能创建一个与对象无关的数组值

对于要作为prvalue的数组,它会留下一个临时对象的
子对象

所以a
tmp

template<typename type>
struct tmp
{
  tmp() {}
  tmp(const tmp &) = default;
  tmp(tmp &&) = default;
  tmp(const tmp &&o):tmp(o) {}
  tmp(tmp &o):tmp(const_cast<tmp const&>(o)){}

  template<class... Ts>
  tmp(Ts&&...ts) : v{std::forward<Ts>(ts)...} {}

  ~tmp () { std::cout << "tmp destructor\n"; }

  type v;
};
template<class X, class... Ts>
tmp<X> wrap_as_tmp(Ts&&... ts)
{
  return {std::forward<Ts>(ts)...};
}
为了跟踪销毁情况,我们使用了噪音

struct noisy {
  ~noisy() { std::cout << "bang\n"; }
};
struct{

~Noised(){std::cout
return tmp();
可能只是
return{};
问题在于第8行返回值的隐式强制转换。忽略函数,根据定义,不能有任何对prvalues的引用。只能有对的引用(可能是临时的)对象。左值和xvalue是对象,prvalue不是。这就是标准化std::array的原因。但仍然没有提供到本机数组的转换。真的太糟糕了。但“C++”从来不是一种基本原理和干净的语言。
struct noisy {
  ~noisy() { std::cout << "bang\n"; }
};
int main() {
  auto&& x = wrap_as_tmp<noisy[4]>().v;
  std::cout << "There\n";
}