How to stop modification of return by reference | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
0

How to stop modification of return by reference

Refer code below: https://www.sololearn.com/compiler-playground/cu36i6R6B3HL Data member m_ConnectionsId of class is very large data and it must also not be modified outside class. To stop modification, I have provided only getIds and no method is given to set Id or modify ids. Only class should handle this as done by method RemoveNonImp. Now my issue is getIds() method. It return reference to avoid unnecessary copy. Doing so, I am able to achieve optimization but now data is exposed to main function as well. Is there a way to achieve stoppage of modification?

1st Apr 2023, 1:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respostas
+ 2
Hello Ketan Lalcheta I don't know if this was right, or whether it was what you mean to do. But anyways, I managed to trigger an exception when a modification was about to happen in main() by specifying both return type of getIds(), and the respective variable receiving the `vector` reference - <connCopy> into `const` Line 23 const vector<int>& getIds() { return m_ConnectionsId; } Line 49 const vector<int>& connCopy = obj.getIds(); With this, an attempt to double the first element fails compilation. Sorry if that's not what you mean. Just wanna share what I found : )
1st Apr 2023, 7:44 PM
Ipang
+ 2
how is it exposed? it is a return value and cannot be modified unless it is by a friend function. Essentially, it is read-only without a write method... edit: oh, I answered without looking at the code, just purely based on your description. I see now that you are talking about vectors and modifying it's content. That's a loophole for getters. In that case, Ipang 's const solution to prevent copying is the way to go.
1st Apr 2023, 2:06 PM
Bob_Li
Bob_Li - avatar
+ 2
Check entire code or atleast output. it is modified already. First value of array is modified from main function.
1st Apr 2023, 2:28 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Ketan Lalcheta I was wondering why would you be going through these elaborate setup. ***** If it is all in your code, JUST DON'T MODIFY IT. ***** If someone has access to your source code, they can modify it as they please and there is really nothing you can do to prevent it.ūüėÖ And if you are doing the modification, then you must have a good reason to contradict yourself... It's like playing "guess what I'm thinking" with yourself. You always win and lose...ūü§£ anyway, the const solution is still not bulletproof. It's no protection if you cast it away. https://code.sololearn.com/cVbEpApB7K61/?ref=app
2nd Apr 2023, 2:22 AM
Bob_Li
Bob_Li - avatar
+ 1
Thats what I was looking for Ipang . Thanks for sharing this
1st Apr 2023, 9:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar