开发者

Returning ref to data from function leads to dangling ref issue

Please check the two code snippets below. While in sample 2, there clearly resides dangling reference issue as ref of local variable is passed, do you think the same problem exists in sample 1? I myself think sample 1 is correct. While data was pushed in data structure (stl::queue), the ref was taken (function header of enqueue is void enqueue(const int &data)). So there should not be problem while returning data through &data here. Or is there?

Sample 1:

int const& dequeue()
{
    _mutex.lock();
    int &data = _queue.back();
    _queue.pop();
    _mutex.unlock();
    return data;
}

Sample 2:

int const& dequeue()
{
    _mutex.lock();
    int data = _queue.back()开发者_如何学JAVA;
    _queue.pop();
    _mutex.unlock();
    return data;
}


Sample 1 is incorrect.

Your reference will become invalid once you call pop().

The reference the function will return must be to an object that is still valid when the function terminates.

This also means that Sample 2 is incorrect, but not for the reason you think. Yes, returning that reference is invalid (it shouldn't even compile), but data is invalid before the end of the function - again, right after the pop() call, any references you have to objects in that container become invalid.

Is there any reason you are returning by reference? You obviously don't expect the value to change at all, and your reference is const, so why not just return by value?

int dequeue()
{
    _mutex.lock();
    int data = _queue.back();
    _queue.pop();
    _mutex.unlock();

    return data;
}

In answer to your more general question, about returning a locally-declared reference, that's fine, as long as the object to which it refers will still be valid once the function terminates. For example:

int glob;

int& f(){
  int x;
  int& ref = glob;
  return x;
}

int main(){
  foo()=10;  //this is fine
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜