casting from 'const string' to a 'non-constant string'

Discussion in 'C++' started by Rene Ivon Shamberger, Oct 19, 2012.

  1. const std::string& someClass::someMethod(){ return some_string = "Bla Bla Bla"; }
    .....
    const std::string& myMethod(){
    someClass obj;
    return obj.someMethod();
    }

    Left as it is, this example will give me a warning stating that the return value from myMethod is a local value, but if I change the code to:

    const std::string&
    someClass::someMethod(){ return some_string = "Bla Bla Bla"; }
    const std::string& myMethod(){
    someClass obj;
    std::string tmp = obj.someMethod(); /// New code
    return temp;
    }
    The compiler complains saying that conversion from 'const string' to 'string' is not permited.
    How can I remove this error?
     
    Rene Ivon Shamberger, Oct 19, 2012
    #1
    1. Advertisements

  2. You should always post code that actually *compiles* rather than typing
    at as you go. (For instance, the name 'temp' is undeclared there.)

    Anyways, I don't see what causes the error message (probably something
    you *didn't* write above), but I do know that you are returning a reference
    to a temporary, which is erroneous. (Undefined behavior, may cause the
    program to crash or misbehave in some othe rway.)
     
    Juha Nieminen, Oct 19, 2012
    #2
    1. Advertisements

  3. What's 'some_string'? A member? A global variable?
    Right after this expression is evaluated and its value is prepared to be
    returned, the 'obj' object is destroyed. *If* 'someMethod' returns part
    of the object for which it's called, as a reference to const, that
    reference becomes *invalid* as soon as 'obj' is destroyed, i.e. outside
    of the 'myMethod' function. IOW, you can't use the return value of the
    'myMethod' function at all - that's undefined behavior.
    On which line? What's 'temp'? Is it a global variable? Where is this
    'myMethod' function defined? A namespace scope or inside another class?
    Don't "remove this error". Code correctly. Do not return references to
    local objects. Ever.

    Also, read the FAQ 5.8.

    V
     
    Victor Bazarov, Oct 19, 2012
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.