Re: reference to non-const temporary
Frederick Gotham wrote:
If you pass either:
(1) non-const reference
(2) pointer to non-const
to a function, then that implies that the function is going to alter
something.
Logic dictates that you only alter something if there's a reason to.
But C++ does not otherwise disallow you from doing things that have no
logical effect. I can do this:
{
auto tmp = make();
use(tmp);
}
even though tmp is guaranteed to disappear just as in
use(make());
The problem is that I cannot see how to correctly write the "fill"
function shown below so that it can work on 'array's and 'array_slice's
(obviously this is a much simplified version of my problem):
//-------------------------------------
struct array_slice {
int* x;
int N;
array_slice(int* x_, int N_) : x(x_), N(N_) {}
int size() const { return N; }
int& operator[](int i) { return x[i]; }
};
template <int N> struct array {
int x[N];
int size() const { return N; }
int& operator[](int i) { return x[i];}
array_slice slice(int start, int size) {
return array_slice(x+start, size);
}
};
template <class A> void fill(A& a) {
for (int i=0; i<a.size(); ++i)
a[i] = i;
}
int main()
{
array<4> a;
fill(a); // Works
fill(a.slice(1,2)); // Fails
}
//-------------------------------------
- Ethan
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]