1

I have a simple assignment function as follows:

LinkedList& LinkedList::operator=(const LinkedList &l) {
    // handle self assignment
    if (this == &l) {
        return *this;
    }

    // free old elements of the list before the new elements from l are assigned
    ~*this();

    // build the list as a deep copy of l (copy constructor handles empty case)
    this(l);

    return *this;
}

and whenever I run my program I get a error: ‘this’ cannot be used as a function response. How do am I supposed to use the constructors in their actual context? Any help is greatly appreciated!

T145
  • 1,206
  • 1
  • 10
  • 31
  • You can just use `std::list`. It is a linked list. – NO_NAME Feb 18 '15 at 22:41
  • 5
    The very idea is bad. See this: http://www.gotw.ca/gotw/023.htm – Fred Larson Feb 18 '15 at 22:42
  • 2
    Just copy and swap. Easier and not broken – Alan Stokes Feb 18 '15 at 22:44
  • NO_NAME: Just trying to learn the tricks of the trade :) @Fred Larson Would making separate functions to handle all of the functionality be better, or could I just use what I have? Maybe in assignment of a new list? Alan Stokes: Where does the "swap" come into play? – T145 Feb 18 '15 at 22:53
  • 2
    @T145: See [another GOTW article for how to use a swap](http://www.gotw.ca/gotw/059.htm). – Fred Larson Feb 18 '15 at 22:55

2 Answers2

3

Manual calling constructors or destructors is almost always a very bad idea. They are not designed to it.

You should create separate functions to clearing and copying the list. Constructor and destructor can use these methods.

NO_NAME
  • 2,769
  • 1
  • 23
  • 56
3

The correct syntax for what you're attempting is:

this->~LinkedList();  
new(this) LinkedList(l);

You've clearly realized that it's good to avoid code duplication, however the preferred way to go about it is to use the copy and swap idiom to write the assignment operator.

Community
  • 1
  • 1
M.M
  • 134,614
  • 21
  • 188
  • 335
  • 1
    I think the destructor/new version is valid code, however if the `new` throws then you end up in a horrible mess, so there is good reason to avoid it. – M.M Feb 18 '15 at 22:58
  • So all I need is `swap(*this, &l); return *this;`? – T145 Feb 18 '15 at 23:04
  • @T145 yes, but without the `&`. And the assignment operator function should take `l` by value (not by reference). – M.M Feb 18 '15 at 23:08
  • Ah yes! Thanks a lot! – T145 Feb 18 '15 at 23:08