std :: cout更改变量值

Atu*_*tul 3 c++ pointers reference

我正在编写我的函数正确返回指向引用的指针.我发现虽然函数返回了它想要做的事情,但是,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;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*136 7

void myfunction(int *&currentIndex, MyClass obj)
{
 currentIndex = &obj.m_Index;
}
Run Code Online (Sandbox Code Playgroud)

调用未定义的行为,因为obj它仅在函数调用的生命周期内有效.你保留一个指向它(或其中一个成员)的指针,它是在它超出范围之后使用的.

您可以通过指向不超出范围的内容来解决(请参阅@ songyuanyao的答案).在这种情况下,不清楚为什么需要指针.myfunction可以只返回索引.


son*_*yao 7

obj参数按值传递,因此将生成一个副本,该函数将在函数退出时销毁.currentIndex被设置为指向无效的地址,并且取消引用它是未定义的行为.它可能运行良好,或者它可能不起作用,一切皆有可能.

一种解决方案是obj通过引用而不是通过值传递:

void myfunction(int *&currentIndex, MyClass& obj)
{
  currentIndex = &obj.m_Index;
}
Run Code Online (Sandbox Code Playgroud)