T145
T145

Reputation: 1523

Properly using constructors in C++

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!

Upvotes: 1

Views: 57

Answers (2)

Piotr Siupa
Piotr Siupa

Reputation: 4838

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.

Upvotes: 3

M.M
M.M

Reputation: 141618

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.

Upvotes: 3

Related Questions