0

Function chaining and data loss

When I started with c++ initially, we were taught that function chaining work only with return value by reference. Otherwise data loss occurs if we use return by value. If I remember correctly, it was for assigning three objects in a single line for assignment operator overloading. Is above still correct? I heard today that builder pattern can return builder object by value and it should not be a problem of data loss. Performance may hit but data loss is not the concern.

21st Jul 2025, 10:04 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
0
can you post a sample code? can you elaborate a bit more about the data loss part? the simplest method chaining implementation I can think at the moment looks something like this: https://sololearn.com/compiler-playground/ck8m0D7ZcEGJ/?ref=app but i would avoid using this pattern because it's harder to debug when something goes wrong.
21st Jul 2025, 1:48 PM
Bob_Li
Bob_Li - avatar
0
Bob_Li thanks for putting this sample code. Why you had returned Car& from all the method ? You could have returned simple car from each method . Is it not necessary to return Car&
21st Jul 2025, 3:16 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Bob_Li here is the trial finally. I could still reproduce this it seems. Means inconsistent behaviour apart from copy constructor cost. Refer code below: https://sololearn.com/compiler-playground/cOYfNI37BKT0/?ref=app It results into data loss. If I had all the methods returning &, we could have proper results.
21st Jul 2025, 3:41 PM
Ketan Lalcheta
Ketan Lalcheta - avatar