Home > database >  why when I create an object of a class on the stack, why it didn't delete after leaving the sco
why when I create an object of a class on the stack, why it didn't delete after leaving the sco

Time:10-21

this is my class

class game
{
private:
    vector<stack> stacks_;
public:
    game();
    void solve();

   friend ostream& operator<<(ostream& os,const game& game);
};

this is the constructor.

game::game()
{
    for (int i = 0; i < 3; i  )
    {
        stack s;
        stacks_.push_back(s);
    }
    cube blueCube(4,0);
    stacks_[0].push(blueCube);

    cube yellowCube(3,1);
    stacks_[0].push(yellowCube);

    cube redCube(2,2);
    stacks_[0].push(redCube);

    cube blackCube(1,2);
    stacks_[0].push(blackCube);
}

in the main function

int main()
{
  game g;

  cout<<g<<endl;

}

after creating the game class why the vector in the game class still have the object. I thought all objects that are declared like that cube blueCube(4,0); without new are on the stack and when I leave the constructor all of them will be deleted. Can anyone explain please ?

CodePudding user response:

I suppose you have a using namespace std; in your code. Don't do that. In the code you posted vector can be std::vector but it could be also something else. I'll asssume it is std::vector. In your code stack cannot be std::stack (it missing a template argument) so it must be something else.

So lets consider this:

{
    stack s;
    stacks_.push_back(s);
}

s will be destroyed when it leaves the scope. push_back stores a copy of s in the vector. All fine. The copy is not affected by deleting the original (unless stack is broken in a weird way. Not respecting the rule of 3/5/0 would cause issues here).

Assuming stack also stores copies of the arguments passed to push_back, the same happens as above. There is no problem with the original cubes getting destroyed.

To avoid the temporaries and the copying you can use emplace_back which, given arguments for the elements constructor, constructs the elements in place.

  • Related