簡體   English   中英

常量正確性導致指針容器出現問題?

[英]Const correctness causing problems with containers for pointers?

鑒於此代碼(使用 C++,Qt 容器,但我認為問題是普遍的):

// 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):

錯誤 C2664:“QList::indexOf”:無法將參數 1 從“const Item *”轉換為“Item *const &”

[
T=項目 *
]
轉換失去了限定符

我認為,由於indexOf()是使用const T &參數聲明的,因此該參數將成為const Item* & (引用指向const Item* &的指針),這很容易從const Item*參數獲得。 不幸的是,由於const T& tT const &t是等價的,出於某種原因,編譯器似乎將參數視為Item* const &t ,它讀作“對指向某個項目的 const 指針的引用”,這是另一回事,而不是使Item指向不可變。

我是否正確解釋了這一點? 為什么即使函數以一種不會改變參數的方式聲明,編譯器也會把事情搞砸? 這真的是 const 語法等價如何把事情搞砸的一個例子嗎? 為什么編譯器使用后一種形式而不是前者? 如果我想在容器中存儲指針並保持嚴格的 const 語義,我該怎么辦?

在這種情況下,您可以使用const_cast刪除const -ness 而不會違反函數的保證。

// 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只是在容器中找到指針,而不是取消引用指針並改變另一側的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM