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

The weird thing is this outputs:奇怪的是这个输出:
* For lookup fucntion: * 对于查找功能:
0x9999999 0x9999999
0x1277777 0x1277777
some_string some_string

* For test code * 用于测试代码
0x9999999 0x9999999
0x1277777 0x1277777
000000000000000000000000000000000000000000 .... 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 .既然你没有共享的功能代码SomeLookUpFunction ,我猜测,你是返回指针类型的局部对象Something This is a bad idea, see similar QA .这是一个坏主意,请参阅类似的 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 .当然,你应该为类型提供拷贝构造函数提高代码something ,甚至提高你的map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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