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

我们两清 提交于 2019-12-11 05:56:10

问题


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

回答1:


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.




回答2:


You're attempting to cast the size_t thing to an r-value, and you can't assign to an r-value.

I have to say that casting away the constness of your size_t member is pretty evil. That's what mutable is for. And AFAICS your 1st const cast does nothing useful.




回答3:


Works this way now...

template<typename T>
const IFixedMemory* FixedMemoryPkt<T>::operator=(const IFixedMemory* srcObj)
{
   this->m_Address = srcObj->GetAddress();
   this->m_Size = srcObj->GetSize();
   return this;
}

template<typename T>
class FixedMemoryPkt : public IFixedMemory
{
private:
    const char* m_Address;
    size_t      m_Size;
};


来源:https://stackoverflow.com/questions/12322179/c-why-i-cant-compile-this-code-what-is-wrong-with-removing-constness-using

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!