简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM