1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. A class holds a std::unique_ptr member and defines its…

Added 30 Nov -0001

A class holds a std::unique_ptr<Impl> member and defines its destructor only in the header as = default. Why does this fail to compile?

  1. The defaulted destructor needs Impl complete to invoke the deleter on it Correct answer
  2. unique_ptr can never hold an incomplete type in any context in C++
  3. The constructor must see Impl to size the pointer, so the definition is needed
  4. The compiler cannot generate a move constructor for an incomplete member

Correct answer

A. The defaulted destructor needs Impl complete to invoke the deleter on it

21 views

MCQSEXAM

Explanation

std::unique_ptr may be declared with an incomplete type, but its destructor instantiates default_delete, which needs the complete type in order to call delete. That is why the pimpl idiom declares ~Widget(); in the header and defines it in the source file after Impl is complete. std::shared_ptr avoids the problem because the deleter is captured and type-erased at construction.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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