首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对数组分段的赋值:这里是否将Rvalue分配给了Rvalue,如果是的话,我如何修复它?

对数组分段的赋值:这里是否将Rvalue分配给了Rvalue,如果是的话,我如何修复它?
EN

Stack Overflow用户
提问于 2015-04-29 23:12:16
回答 1查看 89关注 0票数 0

为了让我的Fortran代码有一天更容易移植到C++,我一直在研究一些表达式模板代码,以提供完整的数组算术操作符,并能够复制和分配指定的较长数组部分。不幸的是,我想不出一个方法来回答我的问题,如果没有一个公平的样板代码,我将尽可能地减少。

首先,我有一个非常简单的‘C样式数组结构’,它封装了一个指针和一个长度,适合在我的混合语言应用程序的C、Fortran、C++和Java部分之间来回传递:

代码语言:javascript
复制
typedef struct {
    int *p;    /*!< Pointer to the data */
    int n;     /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} int_array_C;

typedef struct {
    float *p;    /*!< Pointer to the data */
    int n;       /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} float_array_C;

typedef struct {
    double *p;   /*!< Pointer to the data */
    int n;       /*!< The number of elements; int, not size_t, for Fortran compatibility  */
} double_array_C;

...and等等,用于所有本机类型。然后,根据维基百科关于这个主题的条目中建议的方法定义一些非常简单的表达式模板。

代码语言:javascript
复制
template <typename E, typename T_C >
class VecExpression
{
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;
public:
    //! Returns a const reference to the i'th element in the array
    TT operator[] (int i) const noexcept 
    {
        return static_cast<E const&>(*this)[i];
    }

    //! Returns the total size of the array
    int size() const noexcept
    {
        return static_cast<E const &>(*this).size();
    }

    operator E&() { return static_cast<E&>(*this); }
    operator E const&() const { return static_cast<const E&>(*this); }
};

template <typename E1, typename T_C, typename E2, typename U_C  >
class VecSum : public VecExpression< VecSum<E1, T_C, E2, U_C>, T_C >
{
    E1 const & _u;
    E2 const & _v;
public:
    //! Constructor taking two VecExpressions
    VecSum(VecExpression<E1, T_C> const& u, VecExpression<E2, U_C> const &v) : _u(u), _v(v)
    {
        assert(u.size() == v.size());
    }

    int size() const noexcept { return _v.size(); }

    auto operator[](int i) const
        -> const decltype(_u[i] + _v[i]) { return _u[i] + _v[i]; }
                 // Automatically takes care of type promotion e.g. int to double
                 // according to the compiler's normal rules
};

template <typename E1, typename T_C, typename E2, typename U_C  >
VecSum<E1, T_C, E2, U_C> const operator+(VecExpression<E1, T_C> const &u,
                                         VecExpression<E2, U_C> const &v)
{
    return VecSum<E1, T_C, E2, U_C>(u, v);
}

为了给我一种操作C风格向量内容的方法,我定义了一些模板:一个在预先存在的缓冲区中操作数据,另一个通过使用std::向量来管理自己的内存:

代码语言:javascript
复制
template <typename T_C> class nArray : public T_C, public VecExpression<nArray <T_C>, T_C >
{                                                  // This is the 'curiously recurring template
                                                   // pattern' (CRTP)
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;

    struct startingIndex : public T_C
    {
        size_t start;

        startingIndex(const T_C *initialiser) noexcept
        {
            *(static_cast<T_C *>(this)) = *initialiser;
        }

        nArray to(int element) noexcept
        {
            T_C::n = element - start + 1;
            nArray<T_C> newArray(*(static_cast<T_C *>(this)));
            return newArray;
        }
    };

public:
    //! Constructor to create an nArray from an array_C, without copying its memory
    nArray(T_C theArray) noexcept
    {
        T_C::p = theArray.p;
        T_C::n = theArray.n;
    }

    //! Constructor to create an nArray from an ordinary C array, without copying its memory
    template<std::size_t N>
    nArray(TT (&theArray)[N]) noexcept
    {
        T_C::p = &theArray[0];
        T_C::n = N;
    }

    nArray & operator=(VecExpression<nArray<T_C>, T_C> const& source) &
    {
        // Note that we cannot use the copy-and-swap idiom here because we don't have the means to
        // construct a new temporary memory buffer. Therefore we have to handle the assignment-to-self
        // case explicitly.
        if (&source == this) return *this;
        assert(T_C::n == source.size());
        for (int i=0; i<T_C::n; ++i) T_C::p[i] = source[i];
        return *this;
    }

    //! Copy assignment operator taking a VecExpression of a different (but compatible) type
    //! without allocating any new memory
    template <typename E, typename U_C>
    nArray operator=(VecExpression<E, U_C> const& source) &
    {
        assert(T_C::n == source.size());
        for (int i=0; i<T_C::n; ++i) T_C::p[i] = static_cast<TT>(source[i]);
        return *this;
    }

    //! Returns a non-const reference to the i'th element in the array
    TT& operator[] (int i) noexcept
    {
        return T_C::p[i];
    }

    //! Returns a const reference to the i'th element in the array
    const TT& operator[] (int i) const noexcept
    {
        return T_C::p[i];
    }

    startingIndex from(int element) const noexcept
    {
        startingIndex theNewArray(this);
        theNewArray.p = &T_C::p[static_cast<size_t>(element)];
        theNewArray.n = T_C::n - element;
        theNewArray.start = element;
        return theNewArray;
    }

    nArray to(int element) const noexcept
    {
        nArray theNewArray;
        theNewArray.p = T_C::p;
        theNewArray.n = element + 1;
        return theNewArray;
    }

    // ... and a whole bunch of other functions
};

template <typename T_C> class nVector : public nArray<T_C>
{
    typedef typename std::remove_pointer<decltype(T_C::p)>::type TT;

public:
    template<std::size_t N>
    nVector(TT (&source)[N]) 
    {
        contents.resize(N);
        update_basetype();
        std::copy(&source[0], &source[N], contents.begin());
    }

    // ...and a whole bunch of other constructors and assignment operators
    // which echo those of nArray with the additional step of resizing the
    // internal std::vector and copying the contents into it

private:
    void update_basetype() noexcept
    {
        T_C::p = contents.size() > 0 ? contents.data() : nullptr;
        T_C::n = contents.size();
    }

    std::vector<TT> contents;
};

typedef nArray<float_array_C> float_array;
typedef nVector<float_array_C> float_vector;

// ...and so on

呼!从现在起,我可以做的事情是

代码语言:javascript
复制
float a[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f };
float b[] = { 9.0f, 8.0f, 7.0f, 6.0f, 5.0f, 4.0f };

float_array aArray(a);  // The array contents aren't copied, only
float_array bArray(b);  // the pointers

float_vector aVector = aArray.from(2);  // aVector is { 3.0f, 4.0f, 5.0f, 6.0f }
float_vector bVector = bArray.to(3);    // bVector is { 9.0f, 8.0f, 7.0f, 6.0f } 
float_vector cVector = aArray.from(2).to(4) + bArray.from(1).to(3);
                                        // cVector is { 11.0f, 11.0f, 11.0f } 

...and他们的工作是一种享受。现在,终于,我可以来问我的问题了。假设我想将数组分段分配给一个数组,例如:

代码语言:javascript
复制
float_vector dVector(10);  // An empty 10-element array
dVector.from(3).to(5) = aArray.from(2).to(4) + bArray.from(1).to(3);

事实上,如果我在VisualC++ 2013中编译,这是很好的,但在gcc中却没有。编译在指定任务时失败,并给出如下信息:

代码语言:javascript
复制
error: no match for 'operator=' (operand types are 'nArray<float_array_C>' and 'const VecSum<nArray<float_array_C>, float_array_C, nArray<float_array_C>, float_array_C>')
note: candidates are:
     < ...skipping over a long list of utterly implausible options>
note: nArray<T_C>& nArray<T_C>::operator=(const VecExpression<nArray<T_C>, T_C>&) & [with T_C = float_array_C]
note: no known conversion for implicit 'this' parameter form 'nArray<float_array_C>' to 'nArray<float_array_C>&'

现在,当试图将一个临时对象分配给非const引用时,或者当试图向Rvalue分配一个任务时,这种错误信息似乎会出现在文献中,并且VisualC++在这方面被记录为比gcc更懒散( gcc自然是符合标准的)。我能理解为什么编译器会认为

代码语言:javascript
复制
dVector.from(3).to(5)

作为一名Rvalue,尽管我已经向后弯了腰,试图阻止它的出现。例如,我的startingIndex::to()方法通过值返回nArray对象,而不是引用,如果我编写

代码语言:javascript
复制
auto test1 = dVector.from(3).to(5);
auto test2 = aArray.from(2).to(4) + bArray.from(1).to(3);
test1 = test2;

...then --这很好,编译器告诉我'test1‘是一个'nArray’(即float_array),完全是它应该的样子。

所以,我的问题是:我是否真的因为试图在这里分配一个Rvalue而有罪?如果我是,我如何才能停止这样做,同时仍然能够以这种方式对子数组进行分配,或者至少以某种类似可读的方式进行分配。我真的希望在C++中能以某种方式做到这一点,否则我想我需要回到Fortran-land,写

代码语言:javascript
复制
dVector(3:5) = aArray(2:4) + bArray(1:3)

...and从此过着幸福的生活。

更新

按照Chris的建议,我为进一步的nArray构造函数尝试了几种不同的表单,并确定如下:

代码语言:javascript
复制
nArray && operator=(VecExpression<nArray<T_C>, T_C> const& source) &&
{
    if (&source == this) return *this;
    assert(T_C::n == source.size());
    for (int i=0; i<T_C::n; ++i) T_C::p[i] = source[i];
    return *this;
}

(暂时不需要支持作业自我检查)。gcc编译器似乎忽略了这一点,但我看到的下一个错误是:

代码语言:javascript
复制
no known conversion for argument 1 from 'const VecSum<nArray<float_array_C>, float_array_C, nArray<float_array_C>, float_array_C>' to 'const VecExpression<nArray<float_array_C>, float_array_C>&'

这至少是一种不同的信息(总是进步的标志),但它仍然意味着基本问题是对错误的引用的分配。不幸的是,我不知道该在哪里寻找这个:我的operator+返回是VecSum const &而不是按值返回,但这一点完全没有区别。现在我又被困住了,所以我的下一个策略是在我的Linux分区中安装clang,看看是否从中得到了更有用的错误消息.

进一步更新:

Clang没有什么特别的帮助,它所能说的就是:

代码语言:javascript
复制
candidate function not viable: no known conversion from 'nArray<[...]>' to 'nArray<[...]>' for object argument

这不能给出多少线索!

最终更新:

事实上,回想起来,这个解决方案是多么的明显,我对此感到非常尴尬。我所需要做的就是给我的赋值操作符与普通移动赋值操作符完全相同的形式:

代码语言:javascript
复制
nArray & operator=(VecExpression<nArray<T_C>, T_C> const& source) &&
{
    // Better assignment-to-self check pending...
    assert(T_C::n == source.size());
    for (int i=0; i<T_C::n; ++i) T_C::p[i] = source[i];
    return *this;
}

这当然是克里斯·多德最初提出的逐字建议,在Linux和Windows环境下,clang和gcc的工作非常好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-29 23:40:51

您的nArray赋值操作符:

代码语言:javascript
复制
nArray & operator=(VecExpression<nArray<T_C>, T_C> const& source) &

显式地定义为只应用于lvalue nArray对象(该行中的最终& ),而不应用于rvalue对象,因此不能用于分配给临时片,比如从dVector.from(3).to(5)获得的。您需要一个赋值操作符,其rvalue引用为"this":

代码语言:javascript
复制
nArray & operator=(VecExpression<nArray<T_C>, T_C> const& source) &&

为了能够在这样的临时片上调用这个赋值操作符。

请注意,对于自赋值的&source == this检查是不够的。您可能有不同的nArray对象,它们引用相同的底层存储,具有不同的切片。考虑一下,如果你尝试这样的事情,会发生什么

代码语言:javascript
复制
aVector.from(3).to(7) = aVector.from(1).to(5)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29956226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档