1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. Why does the copy-and-swap assignment operator provide the…

Added 30 Nov -0001

Why does the copy-and-swap assignment operator provide the strong exception guarantee?

  1. Swapping uses move assignment, which the standard requires to be noexcept
  2. The old state is replaced only after the copy has been fully constructed Correct answer
  3. The copy constructor cannot throw once the source object has been locked
  4. It avoids allocating memory, so no allocation failure can occur at all

Correct answer

B. The old state is replaced only after the copy has been fully constructed

55 views

MCQSEXAM

Explanation

Copy-and-swap first builds a complete copy, an operation that may throw while *this remains untouched, and only then swaps the copy with the current state using a non-throwing swap. If anything fails, the object keeps its original value, which is exactly the strong guarantee. The cost is an extra allocation and copy that a self-assignment check or move assignment could avoid, so it trades performance for safety.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs