How to return a copy to keep my data safe?

Hello,

I am practicing algorithms. I want to know how could I return a std::vector in a safe way, such that others have no right to modify it? I use const before the get function, is this the correct way to do this?

class c {
private:
       std::vector<int> v;

       c(int id) {
           this->v.push_back(id);
       }
       ~c();
public:
       const std::vector<int> getV() {
           return this->v;
       }
}
Last edited on
They get a copy of it. The original, inside your class, is safe. What they do with the copy is beyond your control.
you mean i totally do not need the const?
closed account (SECMoG1T)
this is what happens here:

1
2
3
const std::vector<int> getV() {
           return this->v;
       }


- function getV() returns a const qualified copy of the vector, why you decided to const qualify it
i don't get, unless you din't want the caller to modify the copy which isn't memory
efficient at all{what if the vec was a really big container}

- if you want the caller to read and not modify the vector, then the best option would be
1
2
3
const std::vector<int>& getV() { ///const reference, safe and mem efficient
           return this->v;
       }

here a reference to the vector is returned, guarded from modification and no unnecessary
copying is needed

ADVICE:
As @Repeater said when you return a copy, your class data remains safe.
Return a copy if you want the caller to modify it, here your class values
can't be changed and the caller can modify the copy, if you just just want
the caller to read and not modify your class values, return a const reference
Last edited on
When you return anything which is not a reference, the result is a copy of the thing you're returning. So all that const does is prevent modification of the result:
1
2
x.getV().push_back(42); // error.  
// N.B.: x.getV() is a copy of x.v  


And returning a const object doesn't preclude assigning the result to a mutable object.
1
2
const std::vector<int> f() { return {1, 2, 3}; }
int main() { std::vector<int> x = f(); } // just fine  


In general, you should not return types that are qualified with a top-level ( https://stackoverflow.com/questions/7914444/what-are-top-level-const-qualifiers ) const, because doing so prevents binding to rvalue references. This inhibits move semantics and may slow down your code, so probably that's for experts.

Last edited on
Topic archived. No new replies allowed.