In Scott Meyers's "Effective C++" Item 26: Postpone variable definitions as long as possible, the cost of an assignment is not surely less than a constructor-destructor pair.
Then,for different data types or classes, how can I compare the cost of an assignment with a constructor-destructor pair?Which one will be cheaper and why?
In my opinion,constructor-destructor pair need to allocate and deallocate memory,and constructor at least will initialize the variable. But assignment only needs to change the value of variable.
So, I think generally the cost of assignment should be less than a constructor-destructor pair.
I think you've misunderstood the advice. The recommendation is saying it is cheaper to do "construction + destruction" than "default construction + assignment + destruction".
In any case, it's not guaranteed that assignment is cheaper, that's up to the class author. Not all constructors allocate memory, and not all assignments simply "change the value of variable", some assignments re-allocate, or perform non-trivial checks on the value. Also, some assignments are implemented in terms of construction+destruction, as in the copy-and-swap idiom:
T& operator=(const T& t) {
T(t).swap(*this);
return *this;
}
This assignment is certainly not cheaper than construction, because it does construction+swap+destruction.