• Advertisement
Sign in to follow this  

smart pointer on const object

This topic is 4885 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm currently writing a smart pointer to use in our project. There is something that is confusing to me. I create a smart pointer as follows:
SmartPtr<const Classname> name;
The problem is that it is still possible to change the underlying pointer without any complaints by the compiler. Does anybody know a way to overcome that. I read that type traits could do that, but I don't know how and I cannot imagine that I would get the information at compile time. Thanks, Thorris.

Share this post


Link to post
Share on other sites
Advertisement
Hello,

I finally found out why this problem occurs. When declaring the class as const the object itself is really const, but not the pointer on to that object encapsulated in the smart pointer.
But the overall problem remains.

Ciao, Thorris.

Share this post


Link to post
Share on other sites
If you don't want to allow changing the pointer you should declare it as:

const SmartPtr<ClassName> pointer; // similair to ClassName* const

Share this post


Link to post
Share on other sites
Regular and smart pointers both have the same properties in regards to const:

int *intPointer; // Non-constant pointer to non-constant data
SmartPtr<int> intPointer2; // Non-constant smart pointer to non-constant data
const int *intPointer3; // Non-constant pointer to constant data
int const *intPointer4; // Same as above
const SmartPtr<int> intPointer5; // Non-constant smart pointer to constant data
int * const intPointer6; // Constant pointer to non-constant data
SmartPtr<const int> intPointer7; // Constant smart pointer to non-constant data
const int * const intPointer8; // Constant pointer to constant data
const SmartPtr<const int> intPointer9; // Constant smart pointer to constant data

Share this post


Link to post
Share on other sites
Hello,

I know this way, but it works only if there is no access to the underlying pointer. So you could not use typecast operators, but maybe I don't need them.

Ciao, Thorris.

Share this post


Link to post
Share on other sites
Quote:
Original post by Thorris
I know this way, but it works only if there is no access to the underlying pointer. So you could not use typecast operators, but maybe I don't need them.


Good code design can prevent accidents, but it rarely can prevent malice.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement