1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. For std::vector v, how do v.push_back("abc") and…

Added 30 Nov -0001

For std::vector<std::string> v, how do v.push_back("abc") and v.emplace_back("abc") differ?

  1. emplace_back is only valid for trivially copyable types such as int and double values
  2. The two calls are identical in every respect, including the number of constructions
  3. emplace_back builds the string in place from the literal, push_back moves a temporary in Correct answer
  4. emplace_back copies an already-built string object, while push_back builds one from the literal

Correct answer

C. emplace_back builds the string in place from the literal, push_back moves a temporary in

15 views

MCQSEXAM

Explanation

emplace_back forwards its arguments to the element's constructor and builds the object directly in the vector's storage, avoiding the temporary that push_back creates. For a std::string initialised from a literal this usually saves one move or copy. Neither call stops iterators from being invalidated on reallocation, and emplace_back is not always a drop-in replacement when an initializer_list overload exists.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

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