0
class Name_value
{ 
public:
    int value;
    string name;

    Name_value(string a, int b) 
        : name(a), value(b)
    {
    }
    ~Name_value()
    {
        cout << "Object destroyed" << '\n';
    }
};
vector<Name_value> v;
int main()
{
    int score;
    string name;
    
    cout << "Enter a name and value." << '\n';
    while (cin >> name >> score)
    {
        Name_value thedata(name, score);
        v.push_back(thedata);
    }
    for (Name_value x : v)
    {
        cout << x.name << '\n';
    }
}

Output:

Enter a name and value.
c 18
Object destroyed
d 15
Object destroyed
Object destroyed
a 14
Object destroyed
Object destroyed
Object destroyed
b 21
Object destroyed
Object destroyed
Object destroyed
Object destroyed

So my question is what exactly is happening here? Say I type c 18 I create an object put it into the vector and then that object gets destroyed, then I type d 15 which again creates a new object puts it into the vector and destroys it. Why am I getting more destroyed objects everytime?

jaylse2
  • 71
  • 4
  • you should read about move and copy constructor – Federico Oct 08 '21 at 07:56
  • @George The old objects are deleted anyway even when moved. It's the content within that is moved if allowed to do so. If members are trivial in nature, nothing is really saved from a copy anyway. In this case the OP could squeeze a *little* out of this because the string member `name` could be moved. But regardless, even after a move those source objects are still destroyed; they're just (hopefully) shells of their former selves in the process. – WhozCraig Oct 08 '21 at 08:04
  • 1
    Note that if you `reserve` enough storage for vector element and then `emplace_back(name, score)` into `v`, you should observe no destructor call (until the vector itself gets destructed). – Daniel Langr Oct 08 '21 at 08:09
  • 1
    @George Note that one destruction comes from the `thedata` variable in each iteration. Vectors typically double their capacity. – Daniel Langr Oct 08 '21 at 08:11
  • Please note that you can avoid most of the unneded copies: https://godbolt.org/z/WK1eon6f1 – Bob__ Oct 08 '21 at 08:13
  • 1
    I have augmented your MCVE a bit to show more of what's happening: [demo on coliru](http://coliru.stacked-crooked.com/a/64e6b57086fff6fa) – Scheff's Cat Oct 08 '21 at 08:18
  • Why is this question downvoted? It is a valid, more or less well formed beginner's question. It's not a stupid question at all. – Jabberwocky Oct 08 '21 at 08:29
  • 2
    @S.M. you could just edit the title. Shouldn't we be nice to new contributors? – JHBonarius Oct 08 '21 at 08:41
  • 1
    @Jabberwocky yeah my original title was something like "Stupid question about object destruction" so I just edited it myself but feels like a little much to downvote my question just because I had "stupid question" in the title.. – jaylse2 Oct 08 '21 at 08:43

0 Answers0