Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign char* to string without copying [duplicate]

this is quite a simple question, however I'm finding it tricky. I want to treat a char* as if it were a std::string, for instance:

    char *p = ...; // read a huge chuck from a file

    std::string s(p); // this is not what I want

So, if I use the constructor, I get a copy of p, which is a waste of memory and time. Is it possible somehow to avoid this, and "assign" the std::string content to a pre-existing address?

Any other idea is more than welcome!

Thanks!

like image 836
senseiwa Avatar asked Oct 11 '13 13:10

senseiwa


People also ask

Can you convert char * to string?

We can convert a char to a string object in java by using the Character. toString() method.

How do I copy a string into a char pointer?

Syntax: char* strcpy (char* destination, const char* source); The strcpy() function is used to copy strings. It copies string pointed to by source into the destination . This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination .

How to assign one string to another in C?

Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.


1 Answers

Is it possible somehow to avoid this, and "assign" the std::string content to a pre-existing address?

No.

However, you can assign it to a std::string_view. Going forward, all uses of std::string except to own memory should be replaced by std::string_view.

like image 110
Konrad Rudolph Avatar answered Nov 15 '22 17:11

Konrad Rudolph