C ++。为什么我不能编译这段代码?使用const_cast删除const const有什么问题? [英] C++. Why I can't compile this code? What is wrong with removing constness using const_cast?

查看:235
本文介绍了C ++。为什么我不能编译这段代码?使用const_cast删除const const有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题,使用const_cast删除常量。错误msg说转换是一个有效的标准转换.....

I have some problem removing constness using const_cast. Error msg says "Conversion is a valid standard conversion....."

这个问题的性质是什么?为什么要使用C风格的转换?

What is the nature of this problem? Why should I use C-style cast instead?

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

"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_cast 用于将指针或对 const 对象的引用转换为非 - const 等同物。但是,如果对象本身 const ,则不能使用它们修改它们引用的对象。没有有效的方法来修改 m_Size ;如果你想修改它,那么不要声明它 const

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.

分配给指针,因为指针本身不是 const

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

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

如果您确实希望指针本身为 const ,则 *

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

char * const m_Address;

如错误所示,您可以转换 const > value 转换为未经转换的值的非 - const 临时副本但您无法分配到该临时。

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.

这篇关于C ++。为什么我不能编译这段代码?使用const_cast删除const const有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆