Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid conversion from ‘const int*’ to ‘int*’ while taking std::set element address

Tags:

c++

stl

I am getting following error error: invalid conversion from ‘const int*’ to ‘int*’ Following is my program

#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)));
}

I want address of the element in the std::set , This code does not give any compilation error with Microsoft compiler but g++ is giving this compilation error.

like image 654
Avinash Avatar asked Oct 18 '11 05:10

Avinash


Video Answer


1 Answers

It is because each element of std::set is stored as T const, and the implementation has a reason to do so.

Since std::set contains exactly a single copy of a value. It has to make it immutable, otherwise, one can change it's value to something which already exists in the set.

Even if the elements were mutable, you would not be able the change the value, because std::set::find is a const member function, and therefore in this function intSet is immutable and effectively each elements would become immutable as well, including the iterator which it returns, and through which you may change the value at the call-site.

The only want to take the address is this:

int const *paddress =  &(*(intSet.find(4))); //const int* is same as int const*

Don't use const_cast though,

//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
like image 126
Nawaz Avatar answered Nov 15 '22 00:11

Nawaz