PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] How do I make a vector reallocate with out calling a destructor?

 July 07, 2022     c++, c++11, class, destructor, vector     No comments   

Issue

In this code:

Texture * a = new Texture();
Texture * b = new Texture();
buttons.push_back(*a);
buttons.push_back(*b);

buttons is a vector defined like this:

std::vector<Texture> buttons;

Texture is a class and this is its prototype:

class Texture
{
public:
    Picture * texData;
    HitBox * texCoords;
    Texture();
    ~Texture();
    void render_tex();
};

The 4th line of the first code block is calling the destructor for Texture a. The problem is that this destructor deletes the values pointed to by texData and texCoords which means that when it is reallocated texData and texCoords point to junk data.

Is there a way to make it so that the vector will not call the destructor when it reallocates?


Solution

There is a bigger problem here. Since you have a destructor, you will also need to properly implement an assignment operator and copy constructor. Then your code will work fine as is. Google c++ and The Rule of Three. As mentioned, smart pointers could eliminate the need for the big three since they will handle copying and deleting for you behind the scenes.



Answered By - Steger
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing