0
votes

I have had to simplify some of my code to ask this question. However, in the below code does the fact that I am not declaring x as a reference type mean my change of decrementing will get "forgotten" once the function has exited?

The smartest way to fix this would be to declare x as AnotherClass& x?

void MyClass::myFunc(unordered_map<int, AnotherClass>* dictionary, int z, int y){

    AnotherClass x = dictionary->at(z);

    //Does this change on x get "forgotten" in terms of what dictionary stores
    //once myFunc() has finished, because x is not a reference/pointer type?
    x.changeSomething(y--);
}


class MyClass{
    public:

    private:
        myFunc(unordered_map<int, AnotherClass>* dictionary, int z);
        unordered_map<int, AnotherClass>* dictionary

};
2

2 Answers

3
votes

Correct. x is a copy of an element of dictionary. You are applying changes to the copy, which is local to the function. You should see no effects in the caller side. You can either take a reference, or act directly on the result of the call to at:

dictionary->at(z).changeSomething(z--);

Note that this has nothing to do with the code being inside a function.

2
votes

In languages like Java or C# when you write Thing t = s; you are actually creating an alias t that refer to the same object in memory than s refer to. In C++, however, values and aliases are strictly separated:

  • Thing t = s; is about making a copy of s
  • Thing& t = s; is about creating an alias referring to the same object than s (a reference)
  • Thing* t = &s; is about creating an alias referring to the same object than s (a pointer)

The difference between references and pointers does not matter here, what matters is the difference between copies and aliases.

  • Changes to a copy are local to that copy
  • Changes to an object via an alias are local to that object, and visible through all aliases referring to that object

In term of your example:

// Fix 1: take dictionary by *reference* and not by *pointer*.
void MyClass::myFunc(std::unordered_map<int, AnotherClass>& dictionary, int z, int y){
    // Fix 2: dictionary.at(z) returns a "AnotherClass&"
    // that is an alias to the element held within the dictionary.
    // Make sure not to accidentally make a copy by using that "&"
    // for the type of x.
    AnotherClass& x = dictionary.at(z);

    // "x" is now a mere alias, the following call is thus applied
    // to the value associated to "z" within "dictionary".
    x.changeSomething(y--);
}

Note that you could write dictionary.at(z).changeSomething(y--); in this case; however there are several shortcomings:

  • if x is reused more then once, naming it makes it clearer.
  • in cases where the function/method invoked have side-effects, the number of calls is important and need be controlled.
  • from a performance point of view, avoiding unnecessary computing the same thing over and over is always welcome... but don't get too hang up on performance ;)