A
次のような型を作成する方法はありますか?
与えられた:
A f(...);
それで:
両方ともauto&& a = f(...);
コンパイルconst auto& a = f(...);
エラーが発生しますか?
この理由は、この場合、A
は一時的なもの(への引数として提供される)への参照を含む式テンプレートであるf
ため、このオブジェクトの存続期間を現在の式を超えて延長したくないためです。
注:コピーコンストラクターをプライベートにし、必要に応じてAの友達を作成するauto a = f(...);
だけで、問題になるのを防ぐことができます。A
f(...)
コードの例 (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>();
}