example2_usage_with_custom_classes.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
#include <string>

class Person {
public:
    Person(std::string name, int age) : name_(std::move(name)), age_(age) {
        std::cout << "Constructing Person: " << name_ << std::endl;
    }
    
    Person(const Person& other) : name_(other.name_), age_(other.age_) {
        std::cout << "Copying Person: " << name_ << std::endl;
    }
    
    Person(Person&& other) noexcept : name_(std::move(other.name_)), age_(other.age_) {
        std::cout << "Moving Person: " << name_ << std::endl;
    }
    
    friend std::ostream& operator<<(std::ostream& os, const Person& p) {
        return os << p.name_ << " (" << p.age_ << ")";
    }

private:
    std::string name_;
    int age_;
};

int main() {
    std::vector<Person> people;
    
    std::cout << "Using emplace_back:" << std::endl;
    people.emplace_back("Alice", 30);
    
    std::cout << "\nUsing push_back:" << std::endl;
    Person bob("Bob", 25);
    people.push_back(bob);
    
    std::cout << "\nPeople in the vector:" << std::endl;
    for (const auto& person : people) {
        std::cout << person << std::endl;
    }
    
    return 0;
}
Back to emplace_back