鑑於此代碼(C++,使用Qt容器,但我想這個問題是普遍的):Const正確性導致指針容器問題?
// 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的&'
與
[
T =項目*
]
轉換失去限定符
我figurer,由於indexOf()
與const T &
參數聲明的,該參數將成爲一個const Item* &
(參照的指針項這是常量),它是從一個const Item*
參數可以容易地獲得。不幸的是,自const T& t
and T const &t
are equivalent以來,出於某種原因,編譯器似乎將參數視爲Item* const &t
,它讀作「引用指向項目的const指針」,這是不同的事情,並且不會使Item
指向不可變。
我解釋正確嗎?爲什麼編譯器搞砸了,即使函數聲明不會改變參數?這真的是一個const語法等價如何可以搞砸的例子嗎?爲什麼編譯器對前者使用後一種形式?如果我想要將指針存儲在包含器中並保持嚴格的常量語義,我該怎麼辦?
嘗試'items-> indexOf(* item);' –
@MadPhysicist:不起作用,該參數爲'const Item'類型,它不能轉換爲'Item * const&'。 – neuviemeporte
那麼,你的QList是'Item *'列表,而不是'const Item *'。你可以用'QList'逃脫嗎?記住'T *','const T *','T * const'和'const T * const'都是非常不同的東西 –
Mike