0

My code crashes and I think I need to deep copy p_Texture and sprite. I know how to make a deep copy of a pointer to an array but I'm not sure sure how to do this. Here I wrote this destructor:

class Sprite
{
private:
    IDirect3DTexture9* p_Texture;
    LPD3DXSPRITE sprite;
    D3DXVECTOR3 imagepos;
    int m_posX;
    int m_posY;
    int m_posZ;
    int m_width, m_heigth;

public:
    Sprite()
    {
    }

~Sprite()
{
    if (sprite)
    {
        sprite->Release();
        sprite = 0;
    }
    if (p_Texture)
    {
        p_Texture->Release();
        p_Texture = 0;
    }
}

Sprite(std::string path, int posX, int posY, int posZ, int width, int heigth)
{
    m_posX = posX;
    m_posY = posY;
    m_posZ = posZ;
    m_width = width;
    m_heigth = heigth;

    imagepos.x = posX;
    imagepos.y = posY;
    imagepos.z = posZ;

    D3DXCreateTextureFromFileEx(p_Device, path.c_str(), m_width, m_heigth, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
        D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &p_Texture)

    D3DXCreateSprite(p_Device, &sprite)
}

void draw()
{
    sprite->Begin(D3DXSPRITE_ALPHABLEND);
    sprite->Draw(p_Texture, NULL, NULL, &imagepos, 0xFFFFFFFF);
    sprite->End();
}

void incPosX(int x) {imagepos.x += x;}
void decPosX(int x) {imagepos.x -= x;}
void incPosY(int x) {imagepos.y += x;}
void decPosY(int x) {imagepos.y -= x;}

float getPosX() { return imagepos.x; }
float getPosY() { return imagepos.y; }

};

However, it crashes because of copying it in the code.

Mansbota
  • 9
  • 2

1 Answers1

0

The syntax for a copy constructor is:

Sprite::Sprite(Sprite& other)

Then you just copy what you need from other to the this pointer.

Your code as it is right now has an implicit copy and move constructor. Both copy everything by value. The reason for your crashing is likely because somewhere a copy or move of a Sprite is made, and when it expires the destructor is called. This frees some resources which you later attempt to use.

You can find such places by deleteing your copy and move constructors, and seeing where the compiler complains. The syntax follows:

Sprite::Sprite(sprite&  other) = delete; // no copy constructor
Sprite::Sprite(Sprite&& other) = delete; // no move constructor
Ivan Rubinson
  • 3,001
  • 4
  • 19
  • 48