0

テクスチャ クラスに画像ファイルのデータを入力するコードを書いています。私が知る限り、コードと実装は機能しますが、プログラムのメイン ループに入るとセグメンテーション エラーが発生します。次の 4 行を削除すると、セグメンテーション違反が解消されます。

Texture* texture = new Texture(); // Dynamically allocate texture object to texture pointer
bool success = loadTexture(texture, "C:/pathToImage/image.png"); // Function that gets image data
cout << success << endl; // Print out success or not
textures.push_back(*texture); // put texture in a vector of textures

編集: texture.h

class Texture {
public:
    Texture();
    Texture(const Texture&);
    ~Texture();
    Texture& operator=(const Texture&);
public:
    void init();
    int width, height;
    std::vector<unsigned char> pixmap;
    GLuint id;
};

texture.cpp:(エラーに関連しないため、init 関数は編集され、呼び出されません。)

Texture::Texture() : width(0), height(0), pixmap(), id(int(-1)){}
Texture::Texture(const Texture& other) : width(other.width), height(other.height), pixmap(other.pixmap), id(other.id){}
Texture::~Texture()
{
width = 0;
height = 0;
delete &pixmap;
id = int(-1);
}
Texture& Texture::operator=(const Texture& other) {
width = other.width;
height = other.height;
pixmap = other.pixmap;
id = other.id;
}

テクスチャ ポインターと関係があると思いますが、これと同じことを行ういくつかの方法を試しましたが、すべて同じセグメンテーション エラーが発生しました。誰かがこれの原因を説明できますか?

4

2 に答える 2

0

あなたのエラーは、Texture クラスが 3 つのルールに従っていないためです。「デストラクタ、コピー コンストラクタ、または代入演算子のいずれかを持つクラスは、おそらく 3 つすべてを必要とします」。

3つのルールとは?

具体的には、コピーコンストラクターを定義していないため、オブジェクトがベクターに浅いコピーされている可能性があります。これにより、2 つの Texture オブジェクトが同じピックスマップ データを共有することになります。これらのオブジェクトの 1 つが破棄されると、他のオブジェクトのピックスマップ データが無効になります。

たとえば、コピーコンストラクターの1つの可能性はこれです

Texture::Texture(const Texture& other) : width(other.width), height(other.height), pixmap(NULL), id(other.id)
{
    pixmap = new unsigned char[width*height];
    memcpy(pixmap, other.pixmap, width*height);
}

それを行う唯一の方法。cHao は他の可能性を示唆しています。

于 2013-04-28T21:35:37.627 に答える