On 12/20/2017 2:01 PM, ruben safir wrote:
> In a typical syntax for an assignment operator, it might look like this:
>
> T& operator=(const T& other) // copy assignment
> {
> if (this != &other) { // self-assignment check expected
> if (other.size != size) { // storage cannot be reused
> delete[] mArray; // destroy storage in this
> size = 0;
> mArray = nullptr; // preserve invariants in case
> next line throws
> mArray = new int[other.size]; // create storage in this
> size = other.size;
> }
> std::copy(other.mArray, other.mArray + other.size, mArray);
> }
> return *this;
> }
If the `new` expression throws then the current object is left in an
invalid state, with no buffer.
I.e. this code is not exception safe.
One way to fix it: do the allocation before the allocation, and bail out
of it fails (a simple way is to just let the exception propagate).
> I have an example in my code that looks like this:
>
> 143 STATE & operator = (cost b)
> 144 {
> 145 r(b);
> 146 return *this;
> 147 }
This looks like a specialized assignment operator, not a copy assignment.
> So, I've forgotten what this is returning exactly.
The code says it returns a `STATE&`.
> A reference to a pointer to this is being being returned ?
No, a reference to the object that `this` points to.
> what is that?
`this` points to the object that the member function is called on.
Cheers & hth.,
- Alf