I have some problem removing constness using const_cast. Error msg says “Conversion is a valid standard conversion…..”
What is the nature of this problem? Why should I use C-style cast instead?
“error C2440: ‘const_cast’ : cannot convert from ‘const size_t’ to ‘size_t'”
“Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast”
template<typename T>
const IFixedMemory* FixedMemoryPkt<T>::operator=(const IFixedMemory* srcObj)
{
// doesn't remove constness this way. why?
const_cast<char*> (this->m_Address) = (char*)srcObj->GetAddress();
// compile this way, but maybe(?) undefined behaviour
// const_cast<char*&> (this->m_Address) = (char*)srcObj->GetAddress();
// doesn't doesn't work too
const_cast<size_t> (this->m_Size) = (size_t)(srcObj->GetSize());
// const_cast<size_t> (this->m_Size) = 0;
return this;
}
template<typename T>
class FixedMemoryPkt : public IFixedMemory
{
private:
const size_t m_Size;
const char* m_Address;
}
class IFixedMemory
{
public:
virtual const char* GetAddress() const = 0;
virtual size_t GetSize() const = 0;
}
const_castis used to convert from pointers or references toconstobjects, to their non-constequivalents. However, you can’t use them to modify the object they refer to if the object itself isconst. There is no valid way to modifym_Size; if you want to modify it, then don’t declare itconst.You do not need a cast to assign to the pointer, since the pointer itself is not
const:If you did want the pointer itself to be
const, then theconstwould come after the*:and, as with the
const size_t, you wouldn’t be able to reassign it.As the error says, you can convert a
constvalue into a non-consttemporary copy of that value without a cast; but you couldn’t assign to that temporary.