简体   繁体   中英

C++ Vector Size is Zero

I am trying to create a function that renders everything in a vector of displayobject objects (on another thread). I am using SDL thread.

Here is the displayobject.h:

class DisplayObject
{
protected:
    int width;
    int height;
    int x;
    int y;
    SDL_Texture* texture;
    SDL_Renderer* renderer;

public:
    ~DisplayObject();
    int getX();
    void setX(int x);
    int getY();
    void setY(int y);
    int getWidth();
    void setWidth(int width);
    int getHeight();
    void setHeight(int height);
    SDL_Texture* getTexture();
    SDL_Renderer* getRenderer();
};

In graphics.h I have these variables:

std::vector<DisplayObject> imgArr;
SDL_Thread* renderThread;
static int renderLoop(void* vectorPointer);

This code is in the graphics constructor:

TextLabel textLabel(graphics->getRenderer(), 300, 80, "Hallo Welt", 50,       Color(255, 0, 255), "Xenotron.ttf");
//TextLabel inherits from DisplayObject
imgArr.push_back(textLabel);
renderThread = SDL_CreateThread(Graphics::renderLoop, "renderLoop", &imgArr);

This is the render loop function:

int Graphics::renderLoop(void* param)
{
    int counter = 0;
    bool rendering = true;
    std::vector<DisplayObject>* imgArr = (std::vector<DisplayObject>*)param;

    while (rendering)
    {
        cout << imgArr->size() << endl;

        counter++;
        if (counter > 600)
        {
            rendering = false;
        }

        SDL_Delay(16);
    }

    return 0;
}

The problem is that it only prints 0's in the console. Why does it do that? It is supposed to write 1 since I pushed on object into it.

When you insert a TextLabel into std::vector<DisplayObject> , what is stored in the vector is not your original TextLabel object, but a DisplayObject copy-constructed from the TextLabel . What you want to do is create your TextLabel s with new , store pointers to them, and call delete when you no longer need them.

The best solution would be to use boost::ptr_vector<DisplayObject> instead - it will automatically call delete when you erase objects from it. http://www.boost.org/doc/libs/1_57_0/libs/ptr_container/doc/ptr_container.html

If you can't use Boost, but can use C++11, you can use std::vector<std::unique_ptr<DisplayObject>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM