我在使用 const_cast 删除 constness 时遇到了一些问题。错误消息说“转换是有效的标准转换.....”
这个问题的本质是什么?为什么我应该使用 C-style cast 代替?
"error C2440: 'const_cast' : cannot convert from 'const size_t' to 'size_t'"
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;
}