The first time I tried to write a range based for loop to iterate over unique_ptrs I wrote:
std::vector<std::unique_ptr<Foo>> vec;
// Initialize vec
for (auto v : vec) // error
{}
I then realized this is trying to create a copy of each element which doesn't make sense with a unique_ptr. So then I wrote it as a reference:
for (auto& v : vec)
{}
Adding a const in front of it keeps me from changing the pointer.
for (const auto& v : vec)
{
v = nullptr; // error (good!)
}
How can I write it, so that the data pointed to cannot be changed? For example, the following code should not compile.
for (??? v : vec)
{
v->func();
}
class Foo
{
public:
void func();
private:
bool mBar;
}
Foo::func()
{
mbar = true; // Should cause error
}
const(and thus can alter the definition ofvec) or do you only need it to beconstfor this loop ?