About iterator and const problem in C++
class LogManager {
private:
mutable mapManagerMutex mapMutex;
typedef std::map<std::string, LogStorage*> FileNameToStorageClass;
FileNameToStorageClass m_mapFileNameToLogStrg;
public:
int write( const string& strFileName, char* text ) const;
};
int LogManager::write( const string &strFileName, char* text ) const
{
mapManagerMutex::scoped_lock lock(mapMutex);
FileNameToStorageClass::iterator iter;
iter = m_mapFileNameToLogStrg.find(strFileName);
if(iter != m_mapFileNameToLogStrg.end())
{
// do some thing.
}
else
{
return -1;
}
return 0;
}
Above code compiles if i don't have const at end of write function. If i add const at end 开发者_如何转开发i am getting following error
D:/LogManager.cpp:133: error: no match for 'operator=' in 'iter = ((const RtsInfrastructure::RtsCommon::Diagnostics::LogManager*)this)-
cc: C:/QNX650/host/win32/x86/usr/lib/gcc/i486-pc-nto-qnx6.5.0/4.4.2/cc1plus caught signal 1
Does any body know why we are seeing this?
Because m_mapFileNameToLogStrg
is treated as a const member inside the const member function. This is because the type of this pointer is 'LogManager const *'. Then how can the iterator iter
be non-const?
If iter
is non-const, it could be used to modify the member m_mapFileNameToLogStrg
(which is treated as const) thereby violating constness.
So here are a few options:
a) make the member function non-const (write member function being const??)
b) make the string data member mutable.
c) use const_iterator as suggested by Luca Martini
Use FileNameToStorageClass::const_iterator
instead of FileNameToStorageClass::iterator
.
code compiles if i don't have const at end of write function
That tells you that you're doing some non-const operation on a member, such as calling a non-const function. Given the only member you're doing anything to is m_mapFileNameToLogStrg
, check whether its find()
and end()
are const
. Then, as Luca says, the const version of find() should return a const iterator. If you (or your company) have implemented these container types themselves, its quite possible that they don't even have proper const iterators, so you should add them.
精彩评论