繁体   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