在获取std :: set元素地址时,从'const int*'到'int*'的转换无效

Avi*_*ash 5 c++ stl

我收到以下错误 error: invalid conversion from ‘const int*’ to ‘int*’ 以下是我的程序

#include <set>
int main ( int argc, char **argv) {
    std::set<int> intSet;
    intSet.insert(1);
    intSet.insert(2);
    intSet.insert(3);
    intSet.insert(4);
    intSet.insert(5);

    int *pAddress = &(*(intSet.find(4)));
}
Run Code Online (Sandbox Code Playgroud)

我想要的元素的地址std::set,这个代码不会给微软编译器任何编译错误,但是g++给出了这个编译错误.

Naw*_*waz 5

这是因为每个元素std::set都存储为T const,并且实现有理由这样做.

由于只std::set包含一个值的单个副本.它必须使它不可变,否则,人们可以将它的值改为已经存在于集合中的东西.

即使元素是可变的,你也无法改变值,因为它std::set::find是一个const成员函数,因此在这个函数中intSet不可变的,有效的每个元素也会变成不可变的,包括它返回的迭代器,以及通过它您可以更改呼叫站点的值.

唯一想拿地址是这样的:

int const *paddress =  &(*(intSet.find(4))); //const int* is same as int const*
Run Code Online (Sandbox Code Playgroud)

不要使用const_cast,

//DANGEROUS - DONT DO IT
int *paddress =  const_cast<int*>(&(*(intSet.find(4)))); //will compile, 
                                                       //but it is dangerous!

//you might accidentally write
*paddress = 10; //undefined behaviour, 
                //though the compiler will let you write this
Run Code Online (Sandbox Code Playgroud)

  • (实际上,C++ 11允许GCC的行为;看起来我需要更新我的知识) (2认同)