Creating cv::Ptr cause an exception at the end of the application

  aruco, c++, exception, memory, opencv

I am working with openCV arUco markers to detect some markers.
So I generated pre-defined dictionary and saved it in a file.
However the aruco::detectMarkers can only get Ptr<aruco::Dictionary>. So I create a Ptr<aruco::Dictionary> object and sent to the constructor the address of the object itself.
This is causing to exception at the end of the application.
How can I solve it?

Here is my (simplified) code:

#include <opencv2/highgui.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

aruco::Dictionary ReadDictionaryFromFile(std::string fileName)
    cv::FileStorage fileStorage(fileName, cv::FileStorage::READ);
    Mat bytesList;
    int markerSize;
    int maxCorrectionBits;
    fileStorage["markerSize"] >> markerSize;
    fileStorage["maxCorrectionBits"] >> maxCorrectionBits;
    fileStorage["bytesList"] >> bytesList;
    aruco::Dictionary dictionary = cv::aruco::Dictionary(bytesList, markerSize, maxCorrectionBits);

    return dictionary;

int main(int argc, char *argv[])
    //Detector parameters:
    Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
    //This works but I am afraid will generate another dictionary on another machine
    //Ptr<aruco::Dictionary> dictionary = aruco::generateCustomDictionary(1, 4);

    //This works but generate exception when app is terminated
    aruco::Dictionary dictionaryTemp = ReadDictionaryFromFile("Dictionary.yml");
    Ptr<aruco::Dictionary> dictionary = cv::Ptr<aruco::Dictionary>(&dictionaryTemp);

    while (true)
        if (camera.grab(image) != SUCCESS)
            cout << "error on grab()" << std::endl;
            return 0;
        vector< int > ids;
        vector< vector< Point2f > > corners, rejected;
        vector< Vec3d > rvecs, tvecs;

        // detect markers and estimate pose
        aruco::detectMarkers(image, dictionary, corners, ids, detectorParams, rejected);

        aruco::drawDetectedMarkers(image, corners, ids);

        imshow("out", image);
        char key = (char)waitKey(1);
        if (key == 'q')

    return 0;

Here is the exception:

Source: Windows Questions C++