0
我有一個類未能淺拷貝對象
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;
};
和
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;
};
現在我有一個對象RGBHistogram。我想創建像RGBHistogramTrait的100個實例,RGBHistogramTrait的每個實例都應創建RGBHistogram的副本,每個實例將由線程使用。
我會將100個線程的結果彙總回原始RGBHistogram。問題在於,RGBHistogramTrait的每個實例中的_hist都指向相同的東西(原始RGBHistogram)。我以爲我已經在RGBHistogramTrait的構造函數中用_hist(hist)將RGBHistogram淺拷貝了。 RGBHistogram有一個std :: map,沒有定義的複製構件。
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
}