2

Yes I have checked other stackoverflow results: C++ initial value of reference to non-const must be an lvalue

ERROR: initial value of reference to non-const must be an lvalue

Call:

Value& c = getConfigValue("test");

Function:

Value* getConfigValue(const char* name) {
    if (!cleverconfig_loaded) {
        readConfig();
        if (!cleverconfig_loaded) {
            return NULL;
        }
    }
    if (!cleverconfig.HasMember(name)) {
        return NULL;
    }
    return cleverconfig[name];
}

So even after I made the parameter "name" a constant value, it still gives me this error, does anyone know why?

Community
  • 1
  • 1
runefist
  • 543
  • 1
  • 8
  • 19
  • 1
    Your function `getConfigValue` returns a pointer that can not be assigned to a refference. – knivil Feb 20 '17 at 11:48
  • What is this `cleverconfig`? – Chazeon Feb 20 '17 at 11:48
  • 2
    `getConfigValue` is returning a `Value*` and you want to initialize a `Value&`. Did you mean to `*getConfigValue("test")`? – defube Feb 20 '17 at 11:49
  • cleverconfig is a "Document" – runefist Feb 20 '17 at 11:52
  • @defube That would of course fail spectacularly as soon as `getConfigValue` returns a null pointer. – Angew is no longer proud of SO Feb 20 '17 at 11:52
  • @defube, that works, but what does Angew mean with that will fail when it returns null? I can simply check if it is NULL, right? I'm really new to C++ ^^' – runefist Feb 20 '17 at 11:56
  • @runefist Dereferencing a null pointer (that is, applying the `*` to it) results in Undefined Behaviour (which means the program is buggy and can do literally anything). If you want to write correct code, you have to steer clear of UB. BTW, if you're new to C++, you might want to pick up a [good book](http://stackoverflow.com/q/388242/1782465). – Angew is no longer proud of SO Feb 20 '17 at 12:25
  • @runefist It means you'll end up with a null reference. Due to the language rules concerning references, you cannot directly (in general) check if a reference is null. There are ways around this, but my comment was intended to provide the simplest solution to what I thought was causing compilation to fail, not to correct the semantics of your code. – defube Feb 21 '17 at 09:28

1 Answers1

1

The function returns a pointer, which you are trying to bind to a reference. This won't work. How to fix depends on what the return type of cleverConfig.operator[] is - either change the return type of the function from Value* to const Value&, or return *cleverconfig[name];

virgesmith
  • 762
  • 1
  • 7
  • 18