I'm trying to store the content of one string into others. I will have a large number of strings, transferring content in short periods of time, however, I'm questioning the suitability of my method.
For small applications, std::string
works fine, but how would this affect my method under larger cases (in terms of memory)?
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str_a[]{ "Example String" };
string str_b{ str_a };
string str_c{ str_b };
// Print the string
cout << str_a << '\n'
<< str_b << '\n'
<< str_c << '\n';
return 0;
}
OUTPUT:
Example String
Example String
Example String
How would my method benefit if I were to use std::string_view
in terms of memory?
CodePudding user response:
std::string uses static memory allocation which causes overhead on memory when assigning the content to another string. Your current opperation has std::string performing overheads on the memory twice. If your goal is to simply read the string, there is no need for a write operation to be used. Instead of assigning memory multiple times you could use std::string_view to negate this.
Here's an example:
#include <iostream>
using namespace std;
#include <string_view>
// Driver code
int main()
{
string_view str_1{ "Example String" };
string_view str_2{ str_1 };
string_view str_3{ str_2 };
std::cout << str_1 << '\n' << str_2 << '\n' << str_3 << '\n';
return 0;
}
This gives you the same output as before, but this time no more copies of the string, stored in memory.
The std::string_view provides a lightweight object that offers read-only access to a string or a part of a string using an interface similar to the interface of std::_string and merely refers to the shared char sequence.