samedi 28 décembre 2019

Why defining copy constructor gives me error: cannot bind non-const lvalue reference of type 'obj&' to an rvalue of type 'obj'?

#include <iostream>
#include <vector>
#include <array>
#define Nbodies 3

class Assembly {
public:
    // initializing constructor
    Assembly(double _dataA)
        : data(_dataA), AssA(nullptr), AssB(nullptr) { }

    // double argument copy constructor
    Assembly(Assembly &A, Assembly&B)
        : AssA(&A), AssB(&B) {
        data = A.data * B.data;
    }

    // single argument copy constructor - generates errors once uncommented
/*
    Assembly(Assembly &A)
        : data(A.data), AssA(&A), AssB(&A) {
        // initialize other members of this class here
    }
*/
    double data;
private:
    // these are const pointers to non-const objects of a type Assembly
    Assembly *const AssA, *const AssB;
};

int main() {
    std::array<double, Nbodies> datas = {1.0, 2.0, 3.0};

    // Initilize first branch of the binary tree
    std::vector<Assembly> base_assembly;
    for (int i = 0; i < Nbodies; i++) {
        base_assembly.emplace_back(datas[i]);
    }

    // Binary tree assembly - MWE (for general case, I'm using nested for loop)
    Assembly AssemblyAB = Assembly(base_assembly[0], base_assembly[1]);
    Assembly AssemblyC = Assembly(base_assembly[2]);
    Assembly AssemblyS = Assembly(AssemblyAB, AssemblyC);

    std::cout << AssemblyS.data << std::endl;

    return 0;
}

I'm working on a program that generates a binary try recursively. When I have a branch with an odd number of elements, I need to "rewrite" an element to a lower branch. For this, I use a copy constructor since I need to initialize additional members of the class (I'm using the Eigen library, and some operations can not be done as a one-liner in the initialization list).

My problem arose when I defined a singe argument copy constructor. I get the following error:

.../mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_construct.h:75:7: error:

cannot bind non-const lvalue reference of type 'Assembly&' to an rvalue of type 'Assembly'

Why defining a single argument copy constructor generates such an error? Note that in the case of a two-argument copy constructor the are no errors at all.

Aucun commentaire:

Enregistrer un commentaire