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();
_queue.pop();
_mutex.unlock();
return data;
}