开发者

How to return a const ref to a struct object such that all its nested structures also are read only?

开发者 https://www.devze.com 2023-02-22 22:56 出处:网络
How do I prevent all the member variables in a nested struct to be non modifiable? typedef struct A { int a;

How do I prevent all the member variables in a nested struct to be non modifiable?

typedef struct A  
{  
    int a;  
    int b;  
}A1;  

typedef struct B  
{  
    A1* objA;  
}B1;  

class C  
{  
public:  
    const B& GetB() const { return objB; }  
    Po开发者_如何学CpulateB();  

private:  
    B objB;  
};  

int main()  
{  
    C objC;
    objC.PopulateB();  
    const B& objB2 = objC.GetB();  
    objB2.objA->a = 3; // compiler allows this  
}  

I just want a struct that is completely read only and I expected this to work. (In this case objB2)


The pointer is const. The data it points to is not. Thats just how pointers work The best solution is to not expose raw pointers. A non-const accessor function would not be allowed on a const reference, so you can avoid the tricky indirection.

As an aside, you don't have to typedef structs like that. It's a C-ism.


The pointer type in your struct B refers to a non-const value, and this is the definition that counts. If you wanted to control access, you should hide data members and provide accessors and mutators:

struct B
{
private:
    A1* objA;
public:
    A1 & a1() {return *objA;}
    A1 const & a1() const {return *objA;}
};


You can try:

typedef struct B  
{  
    const A1& objA;  
}B1;
0

精彩评论

暂无评论...
验证码 换一张
取 消