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 access b instance passed push(), 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 referenced b:

    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:

  1. dynamically copy b.x. or,
  2. use int const* key. or preferably (avoiding explicit dynamic allocation),
  3. use int key, instead of int* (see http://ideone.com/krykzw)

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -