Search code examples
c++const-cast

C++. Why I can't compile this code? What is wrong with removing constness using const_cast?


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;
}

Solution

  • const_cast is used to convert from pointers or references to const objects, to their non-const equivalents. However, you can't use them to modify the object they refer to if the object itself is const. There is no valid way to modify m_Size; if you want to modify it, then don't declare it const.

    You do not need a cast to assign to the pointer, since the pointer itself is not const:

    this->m_Memory = srcObj->GetAddress();
    

    If you did want the pointer itself to be const, then the const would come after the *:

    char * const m_Address;
    

    and, as with the const size_t, you wouldn't be able to reassign it.

    As the error says, you can convert a const value into a non-const temporary copy of that value without a cast; but you couldn't assign to that temporary.