Domanda

I am using mystr.c_str() function to call write(), open(), etc system calls which need a char* argument. Though because of the nature of .c_str() being a function I suppose call read(rfd, &mystr.c_str(), mystr.lenght()) will not work. What is the best/fast way of implementing this without temporary using char* str?

È stato utile?

Soluzione

You cannot write directly into the buffer of an std::string, as it only ever returns char pointers that point to a read-only string1. Consider using a local array as a buffer. This is about as optimal as you can get without invoking undefined behavior.

const int BUFFER_SIZE = 1024;

char buffer[BUFFER_SIZE];

ssize_t chars_read = read(rfd, buffer, BUFFER_SIZE);

if (chars_read > 0) {
    // To create a new string:
    std::string read_string(buffer, chars_read);

    // To populate an existing string:
    existing_string.assign(buffer, chars_read);
}

1 At least pre-C++11. In C++11 it is safe to use &some_string[0] to get a mutable pointer to the string, but you should ensure that you don't write to &some_string[some_string.size()] or beyond, as this will invoke UB, so you would want to resize() the string first.

Altri suggerimenti

It is not allowed, but it will mostly work (with a const_cast) for most if not all implementations of string, although some implementations will have very very surprising side effects.

Because you are not allowed to write directly to the string returned by c_str(), that allows implementations of string to optimize in various ways. One particular implementation of string I've come accross internally uses a reference counted pointer for copies (only if the size of the string is large). So if you copy the string and then illegally overwrite it's contents, both the original and the copy change.

Even if the string implementation you are currently using survives such abuse, it might later be changed, at which point the program magically starts working in strange ways.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top