Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would the assignment operator ever do something different than its matching constructor?

I was reading some boost code, and came across this:

inline sparse_vector &assign_temporary(sparse_vector &v) {
    swap(v);
    return *this;
}
template<class AE>
    inline sparse_vector &operator=(const sparse_vector<AE> &ae) {
        self_type temporary(ae);
        return assign_temporary(temporary);
    }

It seems to be mapping all of the constructors to assignment operators. Great. But why did C++ ever opt to make them do different things? All I can think of is scoped_ptr?

like image 245
Neil G Avatar asked Jan 22 '23 02:01

Neil G


1 Answers

why did C++ ever opt to make them do different things?

Because assignment works on a fully constructed object. In resource managing classes, this means that every member pointer already points to a resource. Contrast this to a constructor, where the members don't have any meaning prior to executing it.

By the way, in the very early days of C++, T a(b); was actually defined as T a; a = b;, but this proved to be inefficient, hence the introduction of the copy constructor.

like image 178
fredoverflow Avatar answered Feb 11 '23 15:02

fredoverflow