1

I looked through the suggestions but could not find the likes of my error. I ran into this with vs141 and fixed it, I believe by changing the c++ ISO Standard in VS. I may have been too hasty in uninstalling VS2017 when I installed VS2019, so I can't go back to see what I did. It just works with vs140 which I do still have installed. This code will produce the vs142 error:

struct t1{
    t1 append() { return t1(); }
};

struct t2 : public t1{
    t2(t1&te):t1(te){}
    t2 add() { return t1().append(); } //error C2440
};

In my case, t1 is from another library, and I'm wrapping it with t2. I've tried all the variants of c++ ISO Standard in VS2019, but the error persists.

To add to my confusion, I've compiled another project that uses the same code with VS2019, and no error! This Code, line 36. (Note, now there is a problem with boost::fusion and boost::spirit::x3. But that is something else).

What I am doing may be illegal, but when it works, it works fine. And as I don't know for sure, I think it should be fine.

lakeweb
  • 1,859
  • 2
  • 16
  • 21
  • 1
    The only thing I could think of that makes this standard legal would be to change `t2(t1&te):t1(te){}` to `t2(const t1&te):t1(te){}` – UnholySheep Apr 18 '19 at 18:02
  • Also see [this](https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) – rustyx Apr 18 '19 at 18:18

1 Answers1

3

When running this code through a different compiler (such as GCC or Clang) the error message is a bit more helpful:

error: cannot bind non-const lvalue reference of type 't1&' to an rvalue of type 't1'

 t2 add() { return t1().append(); }

This tells you the exact cause:

t2(t1&te):t1(te){}

Accepts a non-const reference, which cannot be a temporary object, such as returned by append() - but a const reference can accept a temporary object, so changing this constructor to

t2(const t1&te):t1(te){}

fixes the problem (and is standard compliant as well)

UnholySheep
  • 3,967
  • 4
  • 19
  • 24
  • Thanks! That does fix it. Why vs142 caught it in two places but not a third... I learned something. And a heads up about the error reporting of Microsoft. There was never mention of `const` in the error message. – lakeweb Apr 18 '19 at 18:20
  • Interestingly enough, when enabling language extensions and using `/W4` instead, MSVC will also warn about the non-`const` reference: https://godbolt.org/z/E6kMj9 - apparently disabling language extension messes with the error detection/reporting – UnholySheep Apr 18 '19 at 18:29