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
ifstatement when there is noifin the code? Moreover, why are you iterating over the list while simultaneously callingpush_fronton it?foolist.emplace_front();(no content in the parens). Note you will need a C++11 toolchain for this to work.emplace_front()like this:emplace_front(foo(args...)). Don't. Call it like this:emplace_front(args...). Ifargs...is nothing, then call it like this:emplace_front()(like I showed in my first comment). Regarding your IDE, make sure-std=c++11is passed as a config switch during compile and link.