Avoid redundant construction/destruction of vector elements

I am wondering if I'm doing it right, with regard to which constructors I need to define to prevent redundant constructions/destructions of objects.
Obviously, it's trivial for an int as the only member variable, but that's just for example.

In the following code,

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
#include <iostream>
#include <vector>

class Base {
public:   
    Base(int id) : id(id) { }
    int id;
};

class Derived : public Base {
public:
    Derived(int id)
    : Base(id) { }
    
    Derived(const Derived& derived)
    : Base(derived.id) { }
    
    Derived(Derived&& derived)
    : Base(derived.id) { }
    
    ~Derived()
    {
        std::cout << "~Derived() " << id << "\n";   
    }
};

void process(const std::vector<Derived>&)
{
    // ...
}

int main()
{
    std::vector<Derived> deriveds = {
        Derived(42),
        Derived(43),
        Derived(44)
    };
       
    process(deriveds);
}

the output is:
~Derived() 44
~Derived() 43
~Derived() 42
~Derived() 44
~Derived() 43
~Derived() 42


Clearly, it's constructing & destructing each element of the vector as a temporary. How can I avoid that?

Edit:
If I attempt to use emplace_back, the behavior is even crazier:
1
2
3
4
    std::vector<Derived> deriveds;
    deriveds.emplace_back(1);
    deriveds.emplace_back(2);
    deriveds.emplace_back(3);

~Derived() 1
~Derived() 2
~Derived() 1
~Derived() 3
~Derived() 2
~Derived() 1

Where did a third (1) come from?? (I know, the moved object should be considered invalid. Point still is it's creating 3 temporaries that I don't want.)

Edit 2:
Only potential fix I can think of would be to add another layer of indirection i.e. making it a vector<pointer>.
Last edited on
Registered users can post here. Sign in or register to post.