gpt4 book ai didi

c++ - std::cout 改变变量值

转载 作者:太空狗 更新时间:2023-10-29 19:41:32 25 4
gpt4 key购买 nike

我正在编写我的函数,它正确地返回了一个指向引用的指针。我发现虽然该函数返回了它应该做的事情,但是 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;
}

最佳答案

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

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

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

关于c++ - std::cout 改变变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38821014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com