Atul
Atul

Reputation: 511

std::cout changing the variable value

I was coding my function is properly returning a pointer to a reference. I found that although the function was returning what it was suppose to do, however, std::cout was modifying the results. Am I doing anything wrong here? How to rectify this behaviour?

Please refer the following code snippet,

#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;
}

Upvotes: 3

Views: 1629

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

The obj parameter is passed by value, so a copy is made that will be destroyed when the function exits. currentIndex is being set to point to an invalid address, and dereferencing it is undefined behavior. It might work well, or it might not work, anything is possible.

One solution is to make obj be passed by reference instead of by value:

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

Upvotes: 7

John3136
John3136

Reputation: 29266

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

Invokes undefined behavior because obj is only valid for the life of the function call. You keep a pointer to it (or one of it's members) which you use AFTER it has gone out of scope.

You can solve either by pointing to something that doesn't go out of scope (see @songyuanyao's answer). In this case it isn't clear why you need pointers. myfunction could just return the index.

Upvotes: 7

Related Questions