Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

OK, so I'm all sold on the copy-and-swap idiom and I think I mostly know how to implement it.

However, or codebase uses MFC's CString class as string and this ain't gonna change.

Since swap must (should???) be nothrow, I cannot do

std::swap(this->my_cstring, rhs.my_cstring);

since that will create a temporary CString object which may throw. (Plus its inefficient.)

So where I'm left? Should I add a try-catch? Should I actually allow this (well, extremely rare) out of memory condition to raise an exception and make swap fail?

Looking at CStrings implementation, it doesn't seem there's a member or function that allows for swapping ...

share|improve this question
    
I can't see a reason to code defensively for out-of-memory. Dealing with it in your CString swap just means it will pop up somewhere else, right? –  Aidan Ryan Oct 5 '11 at 13:34
    
@Aidan: What do you mean by "dealing with it". You simply cannot swap a CString in a 100% exception save manner. –  Martin Ba Oct 5 '11 at 13:37
    
Sorry, I meant, if the only thing your try/catch around the swap could encounter is out-of-memory, there should not be a try/catch because out-of-memory will just crash you elsewhere anyway. –  Aidan Ryan Oct 5 '11 at 13:40

1 Answer 1

up vote 1 down vote accepted

Self-Answer:

After looking into CString more closely, it appears that due to the fact the CString is a reference counted string implementation, swapping it via std::swap is actually "99%" exception safe because all that happens is some reference count increments and decrements.

It's only "99%" safe, as when the CString object IsLocked, it will always do a copy.

share|improve this answer
1  
If not IsLocked and the StringMgrs are the same, then CSimpleStringT::CloneData(CStringData *) simply increases the reference count. –  Daniel Trebbien Oct 5 '11 at 13:55
    
@Daniel - eah, I mentioned IsLocked (which should be rare anyway). I didn't even check anything about StringMgrs. –  Martin Ba Oct 5 '11 at 14:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.