I have a problem trying to dereference an iterator of a std::list<std::unique_ptr<MyClass>>
.
Here's my situation: in headerFile.h I have
class MyClass{
public:
bool variable = false;
private:
};
and then in headerFile2.h
#include "headerFile.h"
#include <memory>
#include <list>
class OtherClass{
public:
private:
std::list<std::unique_ptr<MyClass>> MyList;
void MyFuction();
};
and, finally, in headerFile2.cpp I try to use MyClass::variable like this:
#include "headerFile2.h"
void OtherClass::MyFunction(){
for(auto it = MyList.begin(); it != MyList.end(); it++){
*it -> variable = true;
}
}
It won't compile and I don't know where my mistake is. The error message is
'struct std::_List_iterator<std::unique_ptr<MyClass> >' has no member named 'variable'
I also tried doing **it.variable = true;
.
I would appreciate any advice.
operator->
has higher precedence than operator*
, so *it -> variable = true;
is interpreted as *(it -> variable) = true;
, while it -> variable
is invalid.
You can add parentheses as
(*it) -> variable = true;
**it.variable = true;
has the similar issue; you could (**it).variable = true;
.