Consider a function prototype:
void foo(const std::string& str);
If I call it with a const char*
like this:
const char buffer[] = "Hello World!";
foo(buffer);
will it create a deep copy of the data? Or will it be a shallow copy?
Consider a function prototype:
void foo(const std::string& str);
If I call it with a const char*
like this:
const char buffer[] = "Hello World!";
foo(buffer);
will it create a deep copy of the data? Or will it be a shallow copy?
will it create a deep copy of the data? Or will it be a shallow copy?
It will construct a temporary std::string
object that deep copies the characters from the char[]
into the std::string
.
Copy or not isn't really meaningful here.
A temporary std::string
is constructed and passed to the function (as const reference).
(as a result the buffer
is copied to the std::string
internal buffer.)
you can also pass a std::string_view
, then there would be no copy.
void foo(const std::string_view& str);
will it create a copy of the data?
The char*
that you're passing can be used to create a temporary std::string
using the constructor:
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
but the value category of that object will be rvalue
which cannot bind to an non-const lvalue reference. This means, the given example will not work because a non-const lvalue reference cannot bind to an rvalue.
To solve this, you can add a low-level const in the parameter of the function like :
//-------vvvvv--------------------->low level const added
void foo(const std::string& str);
This works because a const lvalue reference can bind to an rvalue.