This is NOT C++11
I'm interested in the 3rd parameter of Microsoft's CMapStringToOb::GetNextAssoc, which has following definition:
void GetNextAssoc(
POSITION& rNextPosition,
CString& rKey,
CObject*& rValue
) const;
Then I've got following easy code for testing: two good cases and one case with compiler error.
class CMyObject : public CObject //in order to use CMapStringToOb
{
public:
CMyObject(CString name_)
:name(name_)
{
}
void SayHello()
{
TRACE(_T("hello") + name);
}
CString name;
};
void main()
{
CMapStringToOb myMap;
myMap.SetAt(_T("a"), new CMyObject(_T("aaa")));
myMap.SetAt(_T("b"), new CMyObject(_T("bbb")));
myMap.SetAt(_T("c"), new CMyObject(_T("ccc")));
//good case 1
POSITION pos = myMap.GetStartPosition();
while (pos)
{
CString s;
CMyObject* pMine = NULL;
myMap.GetNextAssoc(pos, s, (CObject*&)pMine);
if(pMine)
{
pMine->SayHello();
}
}
//good case 2
pos = myMap.GetStartPosition();
while (pos)
{
CString s;
CObject* pObject = NULL;
myMap.GetNextAssoc(pos, s, pObject);
if(pObject)
{
CMyObject* pMine = static_cast<CMyObject*>(pObject);
pMine->SayHello();
}
}
//bad case:
//can not compile
// error C2440: 'static_cast' : cannot convert from 'CMyObject *' to 'CObject *&'
// static_cast and safe_cast to reference can only be used for valid initializations or for lvalue casts between related classes
pos = myMap.GetStartPosition();
while (pos)
{
CString s;
CMyObject* pMine = NULL;
myMap.GetNextAssoc(pos, s, static_cast<CObject*&>(pMine)); //compile error
if(pMine)
{
pMine->SayHello();
}
}
}
All I was trying to do is find an proper way to replace the C style casting to C++ style cast in this case.
Reading from this, it mentioned:
C casts are casts using (type)object or type(object). A C-style cast is defined as the first of the following which succeeds:
const_cast static_cast (though ignoring access restrictions) static_cast (see above), then const_cast reinterpret_cast reinterpret_cast, then const_cast
Q1: Was the above list missing anything (e.g. for rValue)?
Q2: What's the proper way of translate C style cast to C++ style cast in this case ? (good case 2 works, but, is there a more concise one?)
Q3: How is the C Style cast doing for rValue? (in other words, please explain why good case 1 works)