+ 1
Large string | no deep copy on heap
Hi I have a matrix of string. Few strings are large enough which results into allocation on heap. Now, go to get data function. Is it possible to avoid copy when we fetch data using this function as heap copy is costly? https://code.sololearn.com/cASZO53QlUR2/?ref=app
2 Antworten
+ 3
You can make your get_data function to return a string reference (and raise an exception for incorrect index):
std::string& get_data(int row, int col) {...}
Then if you call it like this:
std::string& res = get_data(i, j);
there will be no new memory allocations.
Depending on what you want you might need to make the return type a const reference to prevent modifying the strings in your matrice.
0
Thanks Volodymyr Chelnokov