简体   繁体   中英

Failed to shallow copy an object

I have a class

template<typename T> class RGBHistogramTrait
{
public:
    RGBHistogramTrait(const QImage &image, RGBHistogram<T> hist) : _hist(hist), _base((QRgb *) (image.bits()));
private:
    const QRgb *_base;
    RGBHistogram<T> _hist;
};

and

template<typename T> struct RGBHistogram
{
    RGBHistogram<T>(Histogram<T> &redHist, Histogram<T> &greenHist, Histogram<T> &blueHist)
        : redHist(redHist), greenHist(greenHist), blueHist(blueHist) {}

    Histogram<T> &redHist, &greenHist, &blueHist;
};

Now i have a single object RGBHistogram. I want to create like 100 instances of RGBHistogramTrait, each instance of RGBHistogramTrait should create a copy of RGBHistogram, each instance will be used by a thread.

I will aggregate the results from the 100 threads back into the original RGBHistogram. The problem is that somehow _hist in each instance of RGBHistogramTrait is pointing to the same thing (the original RGBHistogram). I thought I already shallow copied RGBHistogram in RGBHistogramTrait's constructor by _hist(hist). RGBHistogram has a std::map and no defined copy consturctor.

template<typename T> void ImageReader<T>::calculate(RGBHistogram<T> &hist)
{
    QImage image;

    if (image.load(QString::fromUtf8(_file.c_str())))
    {
        std::vector<RGBHistogramTrait<T> > *fs = new std::vector<RGBHistogramTrait<T> >[_threads];

        for (ThreadNum i = 0; i < _threads; i++)
        {
            fs->push_back(RGBHistogramTrait<T>(image, hist));
        }

        ThreadCoord::start(image.width() * image.height(), _threads, *fs);

        // Now aggregate the results in fs back into the original hist    


        }

Well, you are probably passing the same redHist, greenHist, blueHist by reference in creating RGBHistogram. And redHist, greenHist, blueHist are all reference members. Then of course all 100 RGBHistogram seem to be the same because they all reference the same 3 Histograms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM