简体   繁体   中英

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

我想知道是否可以浅层复制char*std::string

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* .

All the std containers (and std::string is basically a container of char s) do own their data and have value semantics. Thus, no you cannot shallow copy a char* to a std::string out-of-the-box. There are however different objects that can be used for this purpose, to make the difference obvious they are called ..._view , eg since C++17 there is std::string_view .

Technically it should be possible to implement string constructor or member function taking a pointer to buffer (and size / capacity) with ownership transfer (similar to unique_ptr ). However it won't be very helpful since string buffers are supposed to be created by corresponding allocator so you'll end up with calling string allocator manually and / or with difficult to track bugs when pointer passed wasn't created by correct allocator. Also this would make small string optimization problematic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM