簡體   English   中英

C++ const 指針奇怪的行為

[英]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;

奇怪的是這個輸出:
* 對於查找功能:
0x9999999
0x1277777
some_string

* 用於測試代碼
0x9999999
0x1277777
000000000000000000000000000000000000000000 ....

在測試文件中,它給出了很長的零串,但地址是相同的。 知道可能出什么問題了嗎?

既然你沒有共享的功能代碼SomeLookUpFunction ,我猜測,你是返回指針類型的局部對象Something 這是一個壞主意,請參閱類似的 QA

要開始修復您的代碼,您應該首先返回簡單的對象,而不是指針,如下所示:

 // 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 
  }

當然,你應該為類型提供拷貝構造函數提高代碼something ,甚至提高你的map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM