Question 9
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <string>
#include <vector>
struct Person {
std::string name;
Person(std::string n) : name(std::move(n)) { std::cout << "ctor "; }
Person(const Person& o) : name(o.name) { std::cout << "copy "; }
Person(Person&& o) noexcept : name(std::move(o.name)) { std::cout << "move "; }
};
int main() {
std::vector<Person> v;
v.reserve(3);
v.push_back(Person("Asha"));
std::cout << "| ";
v.emplace_back("Ravi");
std::cout << "| ";
Person p("Meena");
v.push_back(p);
std::cout << '\n';
return 0;
}
- A ctor move | ctor | ctor copy Correct
- B ctor | ctor | ctor copy
- C ctor copy | ctor | ctor copy
- D ctor move | ctor move | ctor move
Correct Answer: Option A
push_back(Person(…)) builds a temporary and moves it in; emplace_back builds the element in place; push_back of the lvalue p copies.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!