std::cout 改变变量值

3
我正在编写一个函数,它可以正确地返回一个指向引用的指针。我发现尽管函数返回了它应该返回的内容,但是std::cout却修改了结果。我在这里做错了什么吗?如何纠正这种行为?
请参考以下代码片段:
#include "stdafx.h"
#include <iostream>

using namespace std;
class MyClass
{
 public:
 MyClass(int x_):m_Index(x_){}
 int m_Index;
};

void myfunction(int *&currentIndex, MyClass obj)
{
 currentIndex = &obj.m_Index;
}

int _tmain(int argc, _TCHAR* argv[])
{
  MyClass obj(5);

  int *Index = NULL;
  myfunction(Index, obj);

  int curr_Index = *Index;
  cout << "Index = " << curr_Index << std::endl; // This works fine.
  cout << "Index = " << *Index << std::endl;     // This modifies *Index
  return 0;
}

什么是cout打印,你想要它打印什么? - naffarn
"返回指向引用的指针" -- “我的函数并没有返回任何内容。它的参数类型为指向整型指针的引用。” - Pete Becker
2个回答

7
void myfunction(int *&currentIndex, MyClass obj)
{
 currentIndex = &obj.m_Index;
}

调用未定义行为,因为obj仅在函数调用的生命周期内有效。您保留了对它(或其成员之一)的指针,在它超出范围后继续使用。

您可以通过指向不会超出作用域的内容来解决问题(请参见@songyuanyao的答案)。在这种情况下,不清楚为什么需要指针。myfunction只需返回索引即可。


7

obj参数是按值传递的,因此会复制一份,在函数退出时将被销毁。currentIndex被设置为指向一个无效地址,解引用它是未定义行为。它可能有很好的效果,也可能没有效果,任何结果都有可能。

一个解决方案是将obj改为按引用传递:

void myfunction(int *&currentIndex, MyClass& obj)
{
  currentIndex = &obj.m_Index;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接