James Franco
James Franco

Reputation: 4706

String type alternative in C++

I currently have a function defined in a header that looks like this

void foo::GetValue(std::string& str);

This function basically assigns a value to str. I need to come up with an alternative to str (basically, nothing that employs the standard library).

The implementation of the above function is like this in the .cpp file:

void foo::GetValue(std::string& str)
{
    std::string s = bar.someMethod();
    str = s;
}

I want to know what is the best/easiest option for replacing the header?

One approach I had was to replace std::string in the header file with char* so I would have this in the header:

void foo::GetValue(char* str);

And in the implementation I would have this:

void foo::GetValue(char* str)
{
    std::string resp = bar.someMethod();
    char* c = new char[resp.size() + 1];
    std::copy(resp.begin(), resp.end(), c);
    c[resp.size()] = '\0';
}

The problem with the above approach is that a lot of files are calling this function and they will need to modify their code. Also, they will need to free the above memory. Two concerns I have with this is that other callers to this function will need to do the following two things

  1. Replace std::string being passed to the function with char*.

  2. Free the char* when done using it.

These two items seem very costly to me to trust other callers to do.

Any suggestions on what I can do to solve this problem? Perhaps change the signature to something else? I would prefer if the caller still passes a string, however string.c_str() is a constant char pointer.

Upvotes: 1

Views: 1502

Answers (1)

tadman
tadman

Reputation: 211540

For a given C++ function like this:

std::string foo::GetValue(std::string& str)
{
  return bar.someMethod(str);
}

Then your equivalent C code looks like this:

void foo_GetValue(char* str, char* res, size_t size)
{
  std::string str_arg = str;
  std::string result = bar.someMethod(str_arg);
  strncpy(res, result.c_str(), size - 1);
  res[size-1] = 0; // Ensure is NUL terminated
}

When calling from C:

void example() {
  const BUFFER_LEN = 1024;
  char buffer[BUFFER_LEN];

  foo_GetValue("example", buffer, BUFFER_LEN);
}

Upvotes: 1

Related Questions