C++ std::无法更改变量值

C++ std::无法更改变量值,c++,pointers,reference,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(i

我在编写代码,我的函数正确地返回指向引用的指针。 我发现,尽管函数返回它应该执行的操作,但是,
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;
}
#包括“stdafx.h”
#包括
使用名称空间std;
类MyClass
{
公众:
MyClass(intx_uu):m_索引(x_uu{}
int m_指数;
};
void myfunction(int*¤tIndex,MyClass obj)
{
currentIndex=&obj.m_索引;
}
int _tmain(int argc,_TCHAR*argv[]
{
MyClass obj(5);
int*Index=NULL;
myfunction(索引,obj);
int curr_Index=*Index;
库特
调用未定义的行为,因为
obj
仅在函数调用的生命周期内有效。您保留一个指向它(或它的一个成员)的指针,在它超出范围后使用该指针


你可以通过指向不超出范围的东西来解决(见@songyuanyao的答案)。在这种情况下,您不清楚为什么需要指针。
myfunction
可以直接返回索引。

参数是按值传递的,因此创建的副本将在函数退出时销毁。
currentIndex
被设置为指向无效地址,取消引用它是未定义的行为r。它可能工作正常,也可能不工作,一切皆有可能

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

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

什么是cout打印,您希望它打印什么?“返回指向引用的指针”---“我的函数不返回任何内容。它接受一个类型为指向int的指针的引用的参数。
void myfunction(int *&currentIndex, MyClass& obj)
{
  currentIndex = &obj.m_Index;
}