Search code examples
c++temporary-objects

Why are C++ objects destroyed when initialized inside function? What can I do to prevent it?


Here, when I push to the stack, why are the objects being destroyed?

#include <iostream>
#include <stack>

class One
{
private:
        int i;
public:
        One(int i) {this->i = i;}
        ~One() {std::cout << "value " << this->i << " is destroyed\n";}
};

int main()
{
        std::stack<One> stack;
        stack.push(One(1));
        stack.push(One(2));

        std::cout << "Now I'll stop\n";
}

I expected to see no output before Now I'll stop. But I get this

value 1 is destroyed
value 2 is destroyed
Now I'll stop
value 1 is destroyed
value 2 is destroyed

What should I do if I want prevent them from destroying?


Solution

  • One(1) and One(2) construct two temporary objects, which are passed to push and then copied (moved) into stack. Temporaries are destroyed after the full expression immediately.

    If you want to avoid constructing temporaries you can use emplace instead.

    Pushes a new element on top of the stack. The element is constructed in-place, i.e. no copy or move operations are performed.

    E.g.

    stack.emplace(1);
    stack.emplace(2);