C++中的const_cast

开发环境 Qt Creator 4.8.2

编译器版本 MinGw 32-bit

const_cast

用法:

const_cast<type_id> (expression)

说明:

该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。

常量指针被转化成非常量指针,并且仍然指向原来的对象;常量引用被转换成非常量引用,并且仍然指向原来的对象;常量对象被转换成非常量对象。

如下代码在Qt开发环境中报错

template <typename elemType>
inline elemType* begin_(const vector<elemType> &vec)
{
    return vec.empty() ? 0 : &vec[0];
}
error: cannot initialize return object of type 'int *' with an rvalue of type 'const __gnu_cxx::__alloc_traits<std::allocator<int> >::value_type *' (aka 'const int *')

将代码修改后如下

/*
 * 获取vector的首地址
*/
template <typename elemType>
inline elemType* begin_(const vector<elemType> &vec)
{
    return vec.empty() ? 0 : const_cast<elemType *>(&vec[0]);
}

参考资料:

1 https://www.cnblogs.com/chio/archive/2007/07/18/822389.html 【C++专题】static_cast, dynamic_cast, const_cast探讨