简体   繁体   中英

Will std::string.assign(const char*) or op= ( with const char *) create a copy of the char*?

Digging through the c++ code, it looks like it does a copy, but I cannot be sure. By "copy", I mean something like strcpy is happening internally. And std:string doesn't end up with a pointer to the same char* internally it was passed.

const char *somestring = ...
std::string str;
str.assign(somestring);
// or
str = somestring;  //in my impl, op= calls to assign(const char*)

std::string will always copy from the array pointed to by a char * . You can also provide an iterator range in some constructors.

Copy or reference counting during copies of one std::string to another depends on the C++ library that you are using.

The C++ 2011 standard requires std::string to make real copies. The 2003 standard allowed reference counted copies.

The GNU libstdc++ uses reference counted strings. And for backward compatibility, even the 2011 standard GCC builds with them. Otherwise it couldn't link to code built with the 2003 standard.

There is a preprocessor definition to turn on the new behavior.

See also std::string copy constructor NOT deep in GCC 4.1.2? and Is std::string refcounted in GCC 4.x / C++11?

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