首页 文章

C . 为什么我无法编译此代码?使用const_cast删除constness有什么问题?

提问于
浏览
1

我有一些问题使用const_cast删除constness . 错误消息说“转换是有效的标准转换......”

这个问题的本质是什么?我为什么要使用C风格的演员?

“错误C2440:'const_cast':无法从'const size_t'转换为'size_t'”“转换是一种有效的标准转换,可以隐式执行,也可以使用static_cast,C风格的转换或函数式转换”

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

3 回答

  • 2

    const_cast 用于将指针或对 const 对象的引用转换为非 const 等效项 . 但是,如果对象本身是 const ,则不能使用它们来修改它们引用的对象 . 没有有效的方法来修改 m_Size ;如果你想修改它,那么不要声明它 const .

    您不需要强制转换为指针,因为指针本身不是 const

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

    如果你确实希望指针本身为 const ,则 const 将在 * 之后:

    char * const m_Address;
    

    而且,与 const size_t 一样,您将无法重新分配它 .

    如错误所示,您可以将 const 值转换为该值的非 const 临时副本而不进行强制转换;但你无法分配给那个临时的 .

  • 8

    您正在尝试将size_t事物转换为r值,并且您无法分配r值 .

    我不得不说,抛弃size_t成员的常量是非常邪恶的 . 这就是可变性 . 而AFAICS你的第一个const演员没有任何用处 .

  • 0

    现在以这种方式工作......

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

相关问题