9

Is it OK to pass to function a reference to the value of map element, and to modify it there?

foo(string & s)
{
    s = "xyz";
}

map<int, string> m;
m[1] = "abc";
foo(m[1]); // <-- Is it ok? Will m[1] be "xyz" after this call?

Thank you.

5 Answers 5

10

The answer is Yes.

(operator [] returns a reference)

Sign up to request clarification or add additional context in comments.

Comments

4

Yes, we can.
And it also works with std::vectors (and since it looks like you're using numeric keys, you may consider using them instead).

1 Comment

be careful with vector<bool>::iterator though (dereferencing it does not yield a reference)
2

Yes.

This is no different to typing m[1] = "xyz". The compiler will reduce it all to about the same thing once its finished with it.

Comments

1

A word of advice: You might want to pass it as a pointer rather than a reference. I do that to make it more obvious to the casual reader that it will be changed.

It's all about communicating clearly with the next guy comming down the pike, who has to maintain this code.

But other than that, yeah, it's completely legal code!

2 Comments

I respectfully disagree with your advice. I tend to prefer references unless I am going to supply a null pointer in some instances. Otherwise I'm afraid I am just creating one more possible way to misuse the code, namely with a null pointer instead of a valid reference...
1: You can pass a null reference. It violates language protocol but it can be done. It's using the dereferenced null that coredumps. 2: assert(x!=NULL) has low overhead. 3: At point of call, consider foo(bar); vs foo(&bar);. That & makes it clear bar is changed. My opinion. My $0.02.
0

Yes, it's fine - as everyone already said- and furthermore, your compiler will tell you if it isn't. You may want to experiment a bit; try passing "hello" or (42) to foo(string&) to get a feeling for the warnings your compiler gives you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.