Overloading [ ]

Started by
31 comments, last by perfectly_dark 20 years, 5 months ago
True i guess, but seeing how you should overload operators to mimic the behaviour of the built in types, a good design would probably make operator =, *, !=, ++ no throw.
Advertisement
quote:Original post by dot

No it's not. Let's review it

Assumption of assignments of ref don't throw. What if *it did* ? Construction of array was never completed, new T has *OMFG* succeeded! But since array was never constructed, destructor is *OMFG* never called! so who's freeing the memory pointed to by start? Could it be possible we *do* have a leak? Hmmm… Ooh by the way, not to mention that this is an assignment &#111;n a constructed object. Not very efficient. A better way could be placement new. But that's another story… *since you had to prevent destruction of unconstructed object yet during exceptions…*<br><hr height=1 noshade></SPAN></BLOCKQUOTE><br><br>Placement new is unnecessary here. std::uninitialized_fill() or std::uninitialized_fill_n() should work fine.<br><br><BLOCKQUOTE><SPAN CLASS=smallfont>quote:<hr HEIGHT=1 noshade><br>Same case. Hmmm<br><hr height=1 noshade></SPAN></BLOCKQUOTE><br>Except, here we would use std::uninitialized_copy().<br><br><BLOCKQUOTE><SPAN CLASS=smallfont>quote:<hr HEIGHT=1 noshade> <br>Nice, but not elegant. Now, what if assignment throws again? Exceptions are propagated, yes. But after that, the data in the original array are gone. What if we still need that data?<br><hr height=1 noshade></SPAN></BLOCKQUOTE><br>That's not the big deal here, because the array object is still in a semi-consistent state, i.e. it can still be deleted. The big deal here is that if the new T[] throws, start will have been deleted, but not assigned a new valid value, so the array object is not deletable.<br><br>A better way to handle operator=() would be to copy contruct a temporary array object from the other array, then if that succeeds, swap pointers and sizes with the temporary object. Assuming your copy constructor is exception safe (which we already covered), then that will make operator=() exception safe, transaction safe and &#111;nly three lines of code.<br><br>edit: keep in mind that altering the constructors this way will require the the destuctor be altered as well. <br><br><SPAN CLASS=editedby>[edited by - SiCrane on November 8, 2003 2:17:46 PM]</SPAN>
quote:Original post by Lepton
True i guess, but seeing how you should overload operators to mimic the behaviour of the built in types, a good design would probably make operator =, *, !=, ++ no throw.


Not a practical goal in template programming. For example std::vector<int>::operator=() can throw. So if you had an array<std::vector<int> >, how is it even possible for for array<std::vector<int> >::operator=() not to throw?

This topic is closed to new replies.

Advertisement