Sometimes in a function I use std::move
to pass on a variable I'm no longer using, like this:
void f(std::vector<int> v)
{
for (int i: v)
{
std::cout << i << ", ";
}
}
void main()
{
std::vector<int> v(1000);
std::fill(v.begin(), v.end(), 42);
f(std::move(v));
}
I understand the std::move leaves my vector in a valid state, so I could call v.clear()
and reuse it if I wanted to do so. But in a long function I may later add more code to it and forget that I've lost the data with my move function, introducing a bug.
Is there some kind of compiler instruction I can put after the move to warn me not to reuse this variable? Like this:
void main()
{
std::vector<int> v(1000);
std::fill(v.begin(), v.end(), 42);
f(std::move(v));
#pragma mark_unusable(v);
// This should trigger a compiler warning
v[5] = 10;
}
.clear()
after a move is valid? If not, don't assume that's ok. In any case; how would the compiler know what is valid to do with a type after a move? In short; it cannot know any such thing, so a compiler warning is straight out the window. – Plumberclear()
should be fine,operator[]
not fine. It's a confusing example to have chosen in my question - I'll update it. – Serrulate