Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So I'm working with a function that returns a pointer to a list item. Right now, I'm using:

IYamlEntity* YamlList::operator[](int key)
{
    // Check for out-of-bounds.
    if (key < 0 || key >= _items.size()) return nullptr;
    return &(_items[key]); // **<- Line of interest.**
}

Would the following be better?

IYamlEntity* YamlList::operator[](int key)
{
    // Check for out-of-bounds.
    if (key < 0 || key >= _items.size()) return nullptr;
    return (_items + key); // **<- Line of interest.**
}

I know that they're functionally identical, but which one is "best practice"?

share|improve this question

closed as off-topic by 200_success Mar 1 at 21:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

1  
You're presented two code snippets with one specific difference. According to the help center, "What is the best practice regarding X?" questions are off-topic. – 200_success Mar 1 at 21:42
    
The best one is that one that conveys the most meaning to the reader (not the writer). But the real question is why you are returning a pointer and not a reference. In comparison both the above are worse. – Loki Astari Mar 2 at 16:50
up vote 2 down vote accepted

I would go with:

return (_items + key);

My reason for recommending this is that it is possible to overload the addressof operator, &. If that were the case,

return &(_items[key]);

could potentially be different and incorrect.

Both methods will work equally well if operator& is not overloaded but only the first one will work if it is.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.