const正确性会导致指针容器出现问题? [英] Const correctness causing problems with containers for pointers?

查看:86
本文介绍了const正确性会导致指针容器出现问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码(使用C ++,Qt容器,但我想这个问题是通用的):

Given this code (C++, Qt containers are used but I suppose the question is universal):

// a containter for Item-s
QList<Item*> items;

// argument is const to prevent changing the item by this function
void doStuff(const Item *item)
{
    // find index of the item inside the container
    // indexOf() is declared as:
    // template <typename T> int QList<T>::indexOf(const T &t, int from = 0) const
    const int itemIndex = items->indexOf(item);
}

我收到一个编译错误(MSVC2010):

I get a compile error (MSVC2010):

错误C2664:'QList :: indexOf':无法将参数1从'const Item *'转换为'Item * const&'

[
T =项目*
]
转换失去了限定词

error C2664: 'QList::indexOf' : cannot convert parameter 1 from 'const Item *' to 'Item *const &'
with
[
T=Item *
]
Conversion loses qualifiers

我认为,由于indexOf()是用const T &参数声明的,因此该参数将成为const Item* &(指向const项的指针的引用),可以很容易地从const Item*参数获得.不幸的是,由于 const T& tT const &t是等效的,由于某种原因,编译器似乎将参数视为Item* const &t,其读作为对指向项目的const指针的引用",这是另一回事,并且不会使Item指向不变.

I figurer that since indexOf() is declared with a const T & argument, the argument would become a const Item* & (reference to a pointer to an Item that's const) which is easily obtainable from a const Item* argument. Unfortunately, since const T& t and T const &t are equivalent, for some reason the compiler seems to treat the argument as Item* const &t which reads as "reference to a const pointer to an item" which is a different thing and doesn't make the Item pointed to immutable.

我正确解释了吗?为什么即使函数声明不会改变参数,编译器仍会搞砸呢?这真的是const语法等效性如何弄糟的情况吗?为什么编译器比前者使用后一种形式?如果要将指针存储在容器中并保持严格的const语义,该怎么办?

Am I interpreting this correctly? Why does the compiler screw things up even though the function is declared in a way that says it won't alter the argument? Is this really a case of how the const syntax equivalence can screw things up? Why does the compiler use the latter form over the former? What can I do about it if I want to store pointers in containters and maintain strict const semantics?

推荐答案

在这种情况下,您可以使用const_cast删除const -ness而不会违反功能保证.

This is a case where you can use const_cast to remove the const-ness without violating the guarantee of your function.

// argument is const to prevent changing the item by this function
void doStuff(const Item *item)
{
    // find index of the item inside the container
    // indexOf() is declared as:
    // template <typename T> int QList<T>::indexOf(const T &t, int from = 0) const
    const int itemIndex = items->indexOf(const_cast<Item*>(item));
}

这是因为indexOf只是在容器中找到指针,而不是取消引用指针并改变另一端的内容.

That's because indexOf is merely finding the pointer in the container, not dereferencing the pointer and mutating what's on the other side.

这篇关于const正确性会导致指针容器出现问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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