Passing a struct of dynamic arrays by const reference

375 Views Asked by At

If I have a struct in C++ containing dynamically allocated arrays, for example:

typedef struct foo {
  int* p;
} foo;

foo aFoo;
aFoo.p = new int[n];
for(int i = 0; i < n; ++i)
  aFoo.p[i] = 0;

How can I pass it by reference to a function so that the values stored in aFoo.p[] cannot be modified by the function?

If I declare int func(foo const& aFoo) { ... }, I get a compiler error if I try to modify the pointer aFoo.p, but not if I try to modify, for example, aFoo.p[0]. I'm also allowed to assign a new pointer int* p2 = aFoo.p and modify the values of aFoo.p[] through that.

If I were just passing the pointer, I believe this would be the difference between passing int* const& p and const int* const& p, but I'm not sure how to do it in this situation without declaring member p as a const int* in the struct definition (which would cause complications in other parts of the code).

2

There are 2 best solutions below

1
On

As you have noticed: the pointer cannot be modified, but the contents can.

If you want to keep pointers, I suggest getter/setter:

struct foo {
    void setP(int* p) { this->p = p; }
    int* getP() { return p; }
    const int* getP() const { return p; }
private:
    int* p;
};
1
On

You can forego the pointers and just use std::vector. The following code shows this:

#include <vector>

struct foo {
  std::vector<int> p;
};

void someFunction(const foo& theFoo)
{
    theFoo.p[0] = 10;  // error.
}

int main()
{
   foo aFoo;
   aFoo.p.resize(1);
   someFunction(aFoo);
}

Live example (with compiler error): http://ideone.com/GuJn7d

Live example of pointer (showing no error): http://ideone.com/rVprYZ