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,415
  • 1
  • 13
  • 33

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.

Piotr Siupa
  • 3,929
  • 2
  • 29
  • 65
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
  • 138,810
  • 21
  • 208
  • 365
  • 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