c++11 - C++ 11: conversion const int* to int* using unordered_set::push -
i have problem of conversion code using c++11 standard:
#include<unordered_set> struct b { int x, y; }; class { struct hash { std::size_t operator()( int* const ) const { return std::hash<int>()( *a ); } }; struct equal_to { std::size_t operator()( int* const a, int* const b ) const { return std::equal_to<int>()( *a, *b ); } }; private: std::unordered_set< int*, hash, equal_to > set; public: void push( const b& b ) { set.insert( &b.x ); } };
anyone know why that? can solve problem removing "const" modifier in argument of "push". don't want because argument "b" isn't modified.
edit.: simplification of code has produced unreferenced adress. i've make struct b remove it.
the key of set
declared being pointer-to-int, int*
. this:
void push( const b& b ) { set.insert( &b.x ); }
is passing address of constant int
, int const*
, hence compiler error.
removing const
argument resolve compiler error, making key type int const*
, both these solutions would:
permit other part of program, non-
const
accessb
instance passedpush()
, change value of 1 of keys within set , break set invariant:a a; b b1{17, 22}; b b2{30, 22}; a.push(b1); a.push(b2); b1.x = 30; // set no longer contains unique keys.
introduce dependency of
set
on lifetime of object referencedb
:a a; a.push({14, 23}); // contains dangling pointer.
the safest solution store int
key, see http://ideone.com/krykzw online demo (thanks bitmask comment).
possible solutions:
- dynamically copy
b.x
. or, - use
int const*
key. or preferably (avoiding explicit dynamic allocation), - use
int
key, instead ofint*
(see http://ideone.com/krykzw)
Comments
Post a Comment