c++pointersconst-pointer

C++ const pointers weird behaviour


Class C {
 struct Something {
   string s;
   // Junk.
 }
 // map from some string to something.
 map<string, Something> map;

 // Some more code:
 const Something *Lookup(string k) const {
   const something *l = SomeLookUpFunction();
   cout << l;
   cout << &l->s;
   cout << l->s;
   return l;
  }
}

// Some Test file
const C::Something *cs = C::Lookup("some_key");
cout << cs;
cout << &cs->s;
cout << cs->s;

The weird thing is this outputs:
* For lookup fucntion:
0x9999999
0x1277777
some_string

* For test code
0x9999999
0x1277777
000000000000000000000000000000000000000000 ....

In test file it gives a very long string of zeros, but the addresses are the same. Any idea what could be going wrong ?


Solution

  • Since you have not shared code for function SomeLookUpFunction, I have to guess that you are returning pointer to local object of type Something. This is a bad idea, see similar QA.

    To start fixing your code, you should start by returning simple object, instead of pointer, as shown below:

     // Some more code:
     const Something lookup(string k) const {
       const something l = SomeLookUpFunction(); // return simple object
       cout << &l;
       cout << &l.s;
       cout << l.s;
       return l; // same object 
      }
    

    Of course you should improve the code by providing copy constructors for type something and even improving your map.