samedi 10 juillet 2021

Method returning shared_ptr is called twice at assignment instead of once [closed]

I have a method:

std::shared_ptr<Magick::Image> ImageFile::getImage(){
    auto weakLock = this->weakImage.lock();
    if (weakLock != nullptr){
        return weakLock;
    }
    
    auto imagePointer = std::make_shared<Magick::Image>(this->imagePath);
    this->weakImage = imagePointer;
    return imagePointer;
}

that returns a shared_ptr on request and when calling it with

std::shared_ptr<Magick::Image> thumbnail = (transform.image)->getImage();
// transform.image is an ImageFile pointer

getImage executes fine, but after returning once, it starts at the beginning again crashes at the first line (according to GDB) with no error. However, when running this code:

(transform.image)->getImage();

The method is once again exectued twice, but this time it doesn't crash. No class has a custom copy constructor defined. Why is it executed twice? And how do I fix the crash? Thanks.

EDIT: Working example, as requested in the comments:

#include <memory>
#include <iostream>
#include <Magick++.h>



class ImageFile{

public:
    
    ImageFile(Magick::Image n){
        this->image = n;
    }
    
    std::shared_ptr<Magick::Image> getImage(){
        auto weakLock = this->weakImage.lock();
        if (weakLock != nullptr){
            return weakLock;
        }
        
        auto imagePointer = std::make_shared<Magick::Image>(this->image);
        this->weakImage = imagePointer;
        return imagePointer;
    }
    
private:
    std::weak_ptr<Magick::Image> weakImage;
    Magick::Image image;
};


int main()
{
    Magick::InitializeMagick(nullptr);
    Magick::Image im = Magick::Image("/dir/anyImage.png");
    ImageFile a = ImageFile(im);
    std::shared_ptr<Magick::Image> thumbnail = a.getImage();
    thumbnail->display();
    return 0;
}

In this case, the program doesn't crash, but the method is still executed twice, which is likely the cause of the crash anyways, and is unexpected behavior (at least to me!).

Aucun commentaire:

Enregistrer un commentaire