3

有没有办法创建A这样的类型:

鉴于:

A f(...);

然后:

两者都auto&& a = f(...);给出const auto& a = f(...);编译错误?

这样做的原因是,在这种情况下,A是一个表达式模板,其中包含对临时对象的引用(作为 的参数提供f),所以我不希望这个对象的生命周期超出当前表达式。

请注意,我可以通过将s 复制构造函数设为私有并在需要时与 A 交朋友来防止auto a = f(...);成为问题。Af(...)

代码示例 (ideone链接)

#include <iostream>
#include <array>

template <class T, std::size_t N>
class AddMathVectors;

template <class T, std::size_t N>
class MathVector
{
public:
  MathVector() {}
  MathVector(const MathVector& x) 
  { 
    std::cout << "Copying" << std::endl;
    for (std::size_t i = 0; i != N; ++i)
    {
      data[i] = x.data[i];
    }
  }
  T& operator[](std::size_t i) { return data[i]; }
  const T& operator[](std::size_t i) const { return data[i]; }
private:
  std::array<T, N> data;
};

template <class T, std::size_t N>
class AddMathVectors
{
public:
  AddMathVectors(const MathVector<T,N>& v1, const MathVector<T,N>& v2) : v1(v1), v2(v2) {}
  operator MathVector<T,N>()
  {
    MathVector<T, N> result;
    for (std::size_t i = 0; i != N; ++i)
    {
      result[i] = v1[i];
      result[i] += v2[i];
    }
    return result;
  }
private:
  const MathVector<T,N>& v1;
  const MathVector<T,N>& v2;
};

template <class T, std::size_t N>
AddMathVectors<T,N> operator+(const MathVector<T,N>& v1, const MathVector<T,N>& v2)
{
  return AddMathVectors<T,N>(v1, v2);
}

template <class T, std::size_t N>
MathVector<T, N> ints()
{
  MathVector<T, N> result;
  for (std::size_t i = 0; i != N; ++i)
  {
    result[i] = i;
  }
  return result;
}

template <class T, std::size_t N>
MathVector<T, N> squares()
{
  MathVector<T, N> result;
  for (std::size_t i = 0; i != N; ++i)
  {
    result[i] = i * i;
  }
  return result;
}

int main()
{
  // OK, notice no copies also!
  MathVector<int, 100> x1 = ints<int, 100>() + squares<int, 100>(); 

  // Should be invalid, ref to temp in returned object
  auto&& x2 = ints<int, 100>() + squares<int, 100>(); 
}
4

1 回答 1

5

const&给定任何临时对象,在 C++ 中通过将其绑定到一个或&&变量来延长该临时对象的生命周期始终是合法的。最终,如果您正在处理惰性求值等问题,您必须要求用户不要使用const auto &or auto &&。C++11 中没有任何内容允许您强制阻止用户这样做。

于 2011-10-07T00:51:20.413 回答