在克++爲常量性病,元件接入操作者::矢量<>被定義爲如下:(/usr/include/c++/7.1.1/bits/stl_vector.h
)C++ - 爲什麼std :: vector <> :: const_reference可以強制轉換爲非const指針?
/**
* @brief Subscript access to the data contained in the %vector.
* @param __n The index of the element for which data should be
* accessed.
* @return Read-only (constant) reference to data.
*
* This operator allows for easy, array-style, data access.
* Note that data access with this operator is unchecked and
* out_of_range lookups are not defined. (For checked lookups
* see at().)
*/
const_reference
operator[](size_type __n) const _GLIBCXX_NOEXCEPT
{
__glibcxx_requires_subscript(__n);
return *(this->_M_impl._M_start + __n);
}
但下面的代碼編譯使用g++ -c const-vector.cpp -Wall -pedantic
#include <vector>
void sum(const std::vector<int>& data){
int *ptr;
ptr = (int*) &data[0];
if (data.size()>2)
for (unsigned int i=1;i<data.size();i++)
ptr[0]+=ptr[i];
return;}
所以我沒有問題改變通過const引用傳遞的vector
的內容。
根據cppreference.com,operator[]
超載:
reference operator[](size_type pos);
const_reference operator[](size_type pos) const;
在這種情況下,編譯器將採取第二過載?
1.你可以用casts做很多危險的事情,2.修改const引用傳遞的東西本身並不是一個問題。如果你真的把一個const對象傳遞給這個函數,這隻會是一個問題。 –
另外你的代碼將是UB,如果通過一個空的矢量 –
經典c演員是一個大錘 - 它會做你所說的任何事情。看看static_cast發生了什麼 – pm100