+ 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

21st Jan 2023, 12:53 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Réponses
+ 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.
21st Jan 2023, 8:36 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
22nd Jan 2023, 5:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar