0

In the following code, I have a big vector with 10 members that can be divided into 4 subvectors:

data[10]
P=data[0 to 2]
Q=data[3 to 5]
R=data[6 to 6]
S=data[7 to 9]

Since, vector R only has one member, I prefer to return an rvalue directly from data. I want to do this operation on this value:

x.R()=1983.2+x.R();

like what I can do with Q. But, I receive this error:

g++ -g -c main.cpp -std=c++11 -larmadillo -DNDEBUG
main.cpp: In member function ‘Super_vector::R_type&& Super_vector::R()’:
main.cpp:38:24: error: cannot bind ‘double’ lvalue to ‘Super_vector::R_type&& {aka double&&}’
         return data(6,6);
                        ^
main.cpp: In function ‘int main()’:
main.cpp:52:7: error: using xvalue (rvalue reference) as lvalue
  x.R()=1983.2+x.R();
       ^
make: *** [all] Error 1

main.cpp

#include <armadillo>
#include <iostream>

using namespace std;

typedef arma::vec::fixed<10> x_vec;

class Super_vector
{
public:

    x_vec data;

    typedef decltype(std::declval<x_vec>().subvec(0, 2)) P_type;
    typedef decltype(std::declval<x_vec>().subvec(3, 5)) Q_type;
    typedef double R_type;
    typedef decltype(std::declval<x_vec>().subvec(7, 9)) S_type;

    Super_vector(x_vec data_) :
        data(data_)
    {
    }


    inline P_type P()
    {
        return data.subvec(0,2);
    }

    inline Q_type Q()
    {
        return data.subvec(3,5);
    }

    inline R_type&& R()
    {
        return data(6,6);
    }

    inline S_type S()
    {
        return data.subvec(7,9);
    }

};

int main()
{
    Super_vector x({2,3,5,7,11,13,17,19,23,29});
    x.Q()=-x.Q();
    x.R()=1983.2+x.R();
    x.data.print();

    return 0;
}
cpplearner
  • 13,776
  • 2
  • 47
  • 72
ar2015
  • 5,558
  • 8
  • 53
  • 110
  • Why would you need to return an rvalue in the first place? – Mehrdad Feb 04 '16 at 03:54
  • @MehrdadMomeny, because I want to avoid `subvec` as it is slow and low performance for a single number. Thinking about using this rvalue inside a loop called 1 million times. – ar2015 Feb 04 '16 at 03:56
  • You are returning just a double! there's no such performance issue, I reckon. And then, why don't you just return a lvalue reference? a normal reference. since you want to change the value, don't you? – Mehrdad Feb 04 '16 at 03:58
  • @MehrdadMomeny, Is an lvalue safe here? I tried that and received `what(): Col::operator(): index out of bounds Aborted (core dumped)` – ar2015 Feb 04 '16 at 04:00
  • Well, you have to make sure that `data(6,6)` is returning a reference too! otherwise you can't do what you want here. unless you use another method to get a reference from the data, or modify the value in a different way, and just return the value here. – Mehrdad Feb 04 '16 at 04:03
  • @MehrdadMomeny, You are right. `data(6,6)` was a typo. It must be `data(6)` now it works. – ar2015 Feb 04 '16 at 04:06

0 Answers0