chosenhobo
chosenhobo

Reputation: 25

Using push_front in a for loop doesn't permanently add a member to the list

I am trying to use the push_front() function on a list of a class I created. I have it in a for loop but whenever the loop inserts the new member into the list, it is automatically destroyed right after, I'm assuming because it is out of scope. My question is how do I add these items permanently.

Example:

class foo
{
public:
    foo(){std::cout << "creation" << std::endl;}
    ~foo(){std::cout << "destruction" << std::endl;}
    bool create() {return true;}
};

int main()
{
    std::list<foo> foolist(4);
    for (std::list<foo>::iterator i=foolist.begin(); i!=foolist.end(); i++)
    {
        foolist.push_front(foo());
    }
    return 0;
}

This is the output I'm getting:

creation
creation
creation
creation
creation
destruction
creation
destruction
creation
destruction
creation
destruction
destruction
destruction
destruction
destruction
destruction
destruction
destruction
destruction

When this is what I am trying to achieve:

creation
creation
creation
creation
creation
creation
creation
creation
destruction
destruction
destruction
destruction
destruction
destruction
destruction
destruction

Upvotes: 1

Views: 110

Answers (2)

Brian Bi
Brian Bi

Reputation: 119307

Let's walk through this program one line at a time.

std::list<foo> foolist(4);

Default constructor for foo called 4 times.

foolist.push_front(foo());

This statement runs 4 times. Each time, a foo is default constructed. push_front calls the implicitly defined move constructor in order to move this temporary foo object into the list. (Or the copy constructor if you're still in C++03 mode.) You don't see anything printed, because it's not the default constructor. At the end of each iteration, the temporary foo is destroyed.

    return 0;
}

The list now contains 8 foos, so the destructor is called 8 times.

Upvotes: 5

cppguy
cppguy

Reputation: 3713

The extra "creation" and "destruction" are due to the temp variables you're creating by calling

foo()

Those temp variables get copied into brand new items in the list which ALSO get created when push_front gets called and destroyed when the list falls out of scope

Upvotes: 2

Related Questions