0

What is wrong with this code?

ListADT& ListADT::operator=(ListADT& l2)
{
    ListADT l3;

    for (int i = 0; i < l2.l_size(); i++)
    {
        l3.push_back(l2[i]);
    }
    
    return l3;
} 

It continuously gives me this error:

ListADT.cpp:257:13: warning: reference to local variable ‘l3’ returned [-Wreturn-local-addr]
  257 |      return l3;
      |             ^~
ListADT.cpp:245:14: note: declared here
  245 |      ListADT l3;
      |              ^~
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 6
    What about the warning is not clear? You are returning a *reference* to a local variable. When the function exits, the variable goes out of scope and gets destroyed, causing the returned reference to be left dangling, referencing invalid memory. The caller of the function won't be able to do anything with that reference at all. An `operator=` should be modifying the members of `this` and then using `return *this;` instead. Get rid of `ListADT l3;` altogether – Remy Lebeau Apr 29 '21 at 21:44
  • Or you could try [this one](https://stackoverflow.com/questions/7499864/returning-reference-to-a-local-variable), or the others linked in the comments there, or any of the non-Stack-Overflow results from [copying and pasting `c++ warning undefined reference to local variable returned` into a search engine](https://duckduckgo.com/?q=c%2B%2B+warning+undefined+reference+to+local+variable+returned). Please read [ask] and make sure you understand that you are expected to do some research first. – Karl Knechtel Apr 29 '21 at 21:46
  • Use something more like this instead: `ListADT& ListADT::operator=(const ListADT& l2) { this->clear(); for (int i = 0; i < l2.l_size(); i++) { this->push_back(l2[i]); } return *this; }` – Remy Lebeau Apr 29 '21 at 21:51
  • You should also try to think about *what an `operator=` is supposed to do*. Hint: what does `this` mean in C++? – Karl Knechtel Apr 29 '21 at 21:51

1 Answers1

2

You are returning a reference to a local variable. Once the function exits, that variable will be destroyed, so trying to do something with that reference to a non-existent object is going to cause problems.

Nasrat Takoor
  • 344
  • 3
  • 8
  • This is true, but A) a strong answer provides a solution and B) Remy's warning above about the completely unexpected behaviour of the operator needs to be heeded. `=` should change the object upon which the operator was invoked, not some other instance. A good A will show the asker how to avoid B. – user4581301 Apr 29 '21 at 22:55