2012-08-02 74 views
1

我想通過shared_ptr訪問我以前通過calloc方法分配的數據。出於某種原因,我無法在glTexImage2D(我的代碼片段的最後一行)上訪問它(繼續與EXC_BAD_ACCESS一起崩潰)。通過shared_ptr訪問calloc'd數據

我UTIL方法加載數據:

shared_ptr<ImageData> IOSFileSystem::loadImageFile(string path) const 
{ 
    // Result 
    shared_ptr<ImageData> result = shared_ptr<ImageData>(); 

    ... 

    // Check if file exists 
    if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:NO]) 
    { 
     ... 

     GLubyte *spriteData = (GLubyte*) calloc(width * height * 4, sizeof(GLubyte)); 

     ... 

     // Put result in shared ptr 
     shared_ptr<GLubyte> spriteDataPtr = shared_ptr<GLubyte>(spriteData); 
     result = shared_ptr<ImageData>(new ImageData(path, width, height, spriteDataPtr)); 
    } 
    else 
    { 
     cout << "IOSFileSystem::loadImageFile -> File does not exist at path.\nPath: " + path; 
     exit(1); 
    } 

    return result; 
} 

報頭爲:ImageData

class ImageData 
{ 
public: 
    ImageData(string path, int width, int height, shared_ptr<GLubyte> data); 
    ~ImageData(); 

    string getPath() const; 

    int getWidth() const; 
    int getHeight() const; 

    shared_ptr<GLubyte> getData() const; 

private: 
    string path; 

    int width; 
    int height; 

    shared_ptr<GLubyte> data; 
}; 

文件調用的Util類:

void TextureMaterial::load() 
{ 
    shared_ptr<IFileSystem> fileSystem = ServiceLocator::getFileSystem(); 
    shared_ptr<ImageData> imageData = fileSystem->loadImageFile(path); 

    this->bind(imageData); 
} 



void TextureMaterial::bind(shared_ptr<ImageData> data) 
{ 
    // Pointer to pixel data 
    shared_ptr<GLubyte> pixelData = data->getData(); 

    ... 

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data->getWidth(), data->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixelData); 
} 

只是爲了記錄:如果我拋出所有shared_ptr的我能夠訪問數據。簽名glTexImage2D

void glTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data); 

其它問題:通常你必須釋放(spriteData),但因爲我給數據一個shared_ptr,會當的shared_ptr被刪除的數據來free'd?

+0

我真的不知道代碼是否真的需要所有'shared_ptr'全部。 – 2012-08-02 12:13:21

+0

此外,'ImageData'似乎不遵循[三條規則](http://stackoverflow.com/search?q=%5Bc%2B%2B-faq%5D+rule+of+three)。 – 2012-08-02 12:18:33

+0

@ R.MartinhoFernandes其實我很想知道。我已經開始使用shared_ptr了,因爲大部分內容都非常接近我習慣於Objective-C編碼的方式。所以我幾乎在任何地方使用它們有兩個原因(除了像int這樣的基本類型)。 1.由於自動引用計數和對象的破壞。 2.解決try try和所有可能發生的範圍問題以及autoreleasing可以派上用場。請隨時啓發我我剛開始使用C++;) – polyclick 2012-08-02 12:49:51

回答

3

我覺得這是你的問題:

..., &pixelData); 

你正在服用(的shared_ptr<GLubyte>型)的局部變量的地址,它被悄悄地轉換爲void*,而不是從中獲取指針。替換爲:

..., pixelData.get()); 
+0

非常感謝!不知道當地的範圍東西;)我會記住;) – polyclick 2012-08-02 12:30:25

4

shared_ptr不能奇蹟般地猜測如何釋放內存。默認情況下,它會嘗試delete它,並且由於您沒有使用new,最終會導致災難。

你需要告訴它如何做到這一點:

shared_ptr<GLubyte>(spriteData, &std::free);