Std :: string is assigned by a function returning char *

Update: for the getValue function, I have no control, so what can I do on my part?

I have some kind of silly question about strings and char * basic.

I use a function that returns a char * value,

const char *getValue(const char *key)
{
    //if key found, and valueString is a string
      return valueString.c_str();
    //else
      return NULL;
}

then I initialized the string to store the return value,

std::string value = getValue(key);
Problem

lies in the fact that whenever a value is not found, this means that the function returns NULL, my destination string will be thrown into the exception. But when there is a legitimate cost of return, everything works fine.

I am wondering 1. Is this use completely wrong? Shouldn't I mix char * with string? 2. If not, then when the legal pointer is returned, does my line automatically create a copy and save it? 3. What is the best way to do this?

.

+3
6

, getValue(), NULL, std::string.

std::string value;  // value is an empty string
const char *retVal = NULL;

if( ( retVal = getValue(key) ) != NULL ) {
  value.assign( retVal );
}
+3

, valueString , undefined.

-, , , , .

, , .

+5

goot ( ), NULL. . - NotFoundEx.

, :

const char* getSafeValue(const char *key)
{
  const char* value = getValue(key);
  if(value == NULL)
    throw NotFoundEx();

  return value;
}


std::string value = getSafeValue(key);
+4

std::string, std::string char*:

std::string getValue(const char *key) 
{ 
    if (key found)
        return valueString; 
    else 
        return std::string(); 
} 
0

std::string . (char *) (. boost::optional ), ( , ) - , , (char *) std::string, , " ", , - .

; , , , NULL ( , - ).

0

: ? c_str() ; undefined , . valueString , c_str . , : , , , . ( ) , string, :

std::string
getValue( std::string const& key )
{
    //  ...
    return condition ? valueString : std:;string();
}

, .

value &mdash, , - - .

, . , , ; -, , .

- :

std::string
getValue( std::string const& key, std::string const& ifNotFound )
{
    // ...
    return condition ? valueString : ifNotFound;
}

. , , , , .

The most common alternative is Fallibleeither Maybe class: an object of a class that combines state (usually simple bool) and an instance of the actual data type. Whether the data is valid or independent of the status value, so you still need to check that:

Fallible<std::string>
getValue( std::string const& key )
{
    //  ...
    return condition
        ? Fallible<std::string>( valueString )
        : Fallible<std::string>();
}

This often works well inside too:

Fallible<std::string>
getValue( std::string const& key )
{
    Fallible<std::string> results;
    //  ...
    // At some point, I've got a valid return value, so I do:
        results.validate( valueString );
    // in a condition, of course...
    return results;
}

(Just an example of frequent and convenient patterns.)

0
source

All Articles