Copy happened when pass char * to string?
07:53 27 Aug 2024

I need to call a function whose parameters are of type string.

I thought std::string is a good choice, because it provides a lot of interfaces.

But recently, I found that there is a copy happening when I pass char * to const std::string &.

Here is the code:

#include 
#include 
         
using namespace std;
         
void test_string(const std::string & s) {
  printf("%p\n", s.data());
}        
         
int main() {
  char aa[] = "asd";
  test_string(aa);
  printf("%p\n", aa);
}

As the above code shows, I can pass std::string and char [] to my function test_string.

And since my argument type is const std::string &, I thought that means no copy would happen.

The output shows, however, that the address is different. I think the function constructs a temporary variable string, which copies from my char [] one by one; Which is not necessary.

Is this a bad usage (passing char[] to std::string)? Is there any good advice to avoid copying?

c++ string stl