jeudi 23 juillet 2015

I have a templated class which can (perhaps) be considered as:

template <typename T, size_t fD, size_t mD>
class Field
{
public:
    // Assorted constructors

    // Copy constructor - maybe I've written this horribly?
    Field(const Field<T,fD,mD>& refToCopy) {
        for (size_t d=0; d<fD; d++) {
            field_[d] = refToCopy.field_[d];
        }
    }

    // Const Accessors
    const std::vector<T> &x() const { return field_[0]; }
    // some checking that fD is large enough
    const std::vector<T> &y() const { return field_[1]; }
    // Repeated, non-const.

private:
    std::vector<T> field_[fD];
}

When I try and access the values of a copied field (not one constructed from scratch), I get segfaults. Placing std::cout << "field_[" << d << "][" << i << "] = " << field_[d][i] inside a loop over i inside the copy-constructor also throws this problem (without any output, so presumably on the first value of i...

An example call might be:

Field<double, 2, 2> fieldA(constructor arguments);
Field<double, 2, 2> fieldB(fieldA);
std::cout << "fieldB.x()[5] = " << fieldB.x()[5] << std::endl;

Where did I go wrong? Should I instead seek to use std::array<std::vector<T>>? Is this an invalid way to access a field? Or is my copy-constructor just junk (suspected case).

Aucun commentaire:

Enregistrer un commentaire