How to make it really constant?

S

shuisheng

Dear All,

I have a question. Assume

struct A
{
int *p, *q;
};

struct B
{
A a;

const struct& GetA() const
{
return a;
}
};

I hope B::GetA() cannot change p, q pointed values, but it can, such
as

*(B::GetA().p) = 3;

How can I make it really constant? One way may be defining p and q as
follows
const int * p;
const int * q;

Whenever p, q pointed values want to change in class/struct A, do the
const_cast. But this is too cumbersome.

I remember a constant std::vector cannot change its values, even
thought it is also implemented by a inner pointer. How does
std::vector make the values constant?

Thanks and best regards,

Shuisheng
 
T

tony_in_da_uk

Dear All,

I have a question. Assume

struct A
{
int *p, *q;

};

struct B
{
A a;

const struct& GetA() const
{
return a;
}

};

I hope B::GetA() cannot change p, q pointed values, but it can, such
as

*(B::GetA().p) = 3;

How can I make it really constant? One way may be defining p and q as
follows
const int * p;
const int * q;

Whenever p, q pointed values want to change in class/struct A, do the
const_cast. But this is too cumbersome.

If you want this kind of control, you should make A a class, with p
and q private. Then provide const A& get_a() const and A& get_a()
members etc..

Tony
 
A

anon

If you want this kind of control, you should make A a class, with p
and q private. Then provide const A& get_a() const and A& get_a()
members etc..

With this solution you can still change values. In the
const A& get_a() const
method, you couldn't change pointers, but could still change the value
they point to.

Only way is to change struct A
 
T

tony_in_da_uk

With this solution you can still change values. In the
const A& get_a() const
method, you couldn't change pointers, but could still change the value
they point to.

Only way is to change struct A [snip]

"If you want this kind of control, you should make A a class, with p
and q private."...

struct A
{
private:
int *p, *q;
};

"Then provide const A& get_a() const and A& get_a() members etc.."...

struct B
{
A a;
const struct& GetA() const
{
return a;
}

struct& GetA()
{
return a;
}
};

Clearly, there's nothing public to access in a. By implication, you
must expose p and q similarly...

struct A
{
const int* get_p() const { return p; }
int* get_p() { return p; }

const int* get_q() const { return q; }
int* get_q() { return q; }

private:
int *p, *q;
};

And there you have it.

Tony
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top