2015-03-31 146 views
2

我想創建一個函數,呈現displayobject對象(在另一個線程上)的向量中的所有內容。我正在使用SDL線程。C++矢量大小爲零

這裏是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(); 
}; 

在graphics.h中我有這些變量:

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

此代碼是在圖形構造:

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); 

這是渲染循環功能:

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; 
} 

問題是它只在控制檯打印0。它爲什麼這樣做?它應該寫1,因爲我把對象放入它。

+1

在一個不相關的點上,僅僅因爲一個函數想要一個指針參數並不意味着你傳遞的變量必須是一個指針。在需要時,可以使用地址 - 運算符'&'來創建一個指向變量的指針。 – 2015-03-31 16:40:41

+1

'新的std :: vector'通常是錯誤的。爲什麼不只是'std :: vector imgArr;'? – 2015-03-31 16:42:06

+0

@NeilKirk現在編輯 – 2015-03-31 16:48:36

回答

3

當你插入一個TextLabelstd::vector<DisplayObject>,什麼是存儲在向量是不是你原來的TextLabel對象,但是從TextLabel一個DisplayObject拷貝構造。你想要做的就是用new創建TextLabel,存儲它們的指針,並在你不再需要時調用delete

最好的解決方案是使用boost::ptr_vector<DisplayObject>代替 - 當您從中刪除對象時,它會自動調用deletehttp://www.boost.org/doc/libs/1_57_0/libs/ptr_container/doc/ptr_container.html

如果您不能使用Boost,但可以使用C++ 11,則可以使用std::vector<std::unique_ptr<DisplayObject>>