Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shallow copy char* to std::string?

Tags:

c++

string

I wonder if it's possible to shallow copy char* to std::string.

like image 430
Zack Lee Avatar asked Aug 15 '18 09:08

Zack Lee


People also ask

Does std::string copy char *?

If you aim at constructing a std::string object with a char* without copying the data: no, this is impossible. std::string owns its resources, it can't refer to another char* . This is also why the appropriate constructor takes a const char* , not a char* : it doesn't modify the data, but copies it.

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.


1 Answers

If you aim at constructing a std::string object with a char* without copying the data: no, this is impossible. std::string owns its resources, it can't refer to another char*. This is also why the appropriate constructor takes a const char*, not a char*: it doesn't modify the data, but copies it.

In C++17, you have std::string_view which is exactly meant for referring to a string (literal) that it doesn't own. Note that this view isn't intended to modify the data, its hence constructed with const char* again, not char*.

like image 79
lubgr Avatar answered Sep 19 '22 07:09

lubgr