1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. A shared_ptr is built as std::shared_ptr(new int[10])…

Added 30 Nov -0001

A shared_ptr is built as std::shared_ptr<int>(new int[10]). What happens when the last reference to it goes away?

  1. Plain delete is called on the array pointer, which is undefined behaviour Correct answer
  2. delete[] is chosen automatically because the pointer type is an array
  3. The control block detects the array and calls the array deleter for you
  4. Nothing is freed, because shared_ptr never deletes array allocations at all

Correct answer

A. Plain delete is called on the array pointer, which is undefined behaviour

20 views

MCQSEXAM

Explanation

std::shared_ptr stores a deleter chosen at construction, and the default one calls delete rather than delete[]. Constructing it from new int[10] therefore mismatches the allocation and deallocation forms, which is undefined behaviour. C++17 added shared_ptr<T[]> and make_shared<T[]> for the common case, and a custom deleter works on older standards.

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