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探讨

原文链接: https://www.cnblogs.com/Manual-Linux/p/10990893.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中的const_cast

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/296407

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午5:52
下一篇 2023年2月15日 下午5:52

相关推荐