-1
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
0000000000000000000000000000000000000000000 ....

在测试文件中,它给出了一个很长的零字符串,但地址是相同的。知道可能出了什么问题吗?

4

1 回答 1

0

由于您没有共享函数代码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.

于 2016-03-08T08:29:40.103 回答