Kefir
Kefir

Reputation: 125

Local copy of array Element

To make my code more readable, i have a local variable inside a function, that takes a specified element from an array, like this:

Element* elements = new Element[10];

void doSomething(int index) {
    Element element = elements[index];
    // do things with that element
}

What happens here: is element an independent copy of elements[index] that gets destroyed at the end of the function? From what I've tested, it seems like it, as changes in element don't affect element[index], however, I'd like to know what's happening behind the scenes. Does the assignment of element call an implicit copy constructor?

Upvotes: 2

Views: 312

Answers (2)

Akash
Akash

Reputation: 76

Yes, the local variable "element" is independent of global "elements pointer". Changes in local value will not change the global value.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254471

Yes, that's exactly what happens (although this is an initialisation, not an assignment).

You've declared Element to be an object, so it's a separate object from any other Element. It's initialised by copying its initialiser elements[index]. If you haven't delcared a copy-constructor, then it uses the implicit one, copying each member.

If you wanted to modify the element in the array, then you'd want a reference:

Element & element = elements[index];
        ^

Upvotes: 8

Related Questions