P
pauldepstein
My text is the 4th ed. of C++ Primer by Lippman, Lajoie and Moo. I
have a question about the following smart pointer code from this text:
class U_Ptr
{friend class HasPtr;
int* ip;
size_t use;
U_Ptr(int* p): ip(p), use(1) {}
~U_Ptr() { delete ip;}
};
class HasPtr{
public:
void set_ptr(int* p) {ptr -> ip = p;} // THIS IS A NON_CONST METHOD
private:
U_Ptr* ptr;
// Public and private methods and members continue
};
Later in the text, a different implentation of HasPtr is given:
class HasPtr{
public:
HasPtr(const int& p, int i): ptr(new int(p)), val(i) {}
private:
int* ptr;
int val;
public:
void set_ptr_val(int p) const { *ptr = p; } //CONST METHOD
// Public and private methods and members continue
};
As I see it set_ptr and set_ptr_val don't change their class members
and can both legally be labelled const.
Some might choose to make the pointer-setting methods non-const
according to the logic that data is being changed through the pointer
so the set_ptr methods might be said to be conceptually non-const.
It seems very strange to me to make one of the pointer-setting methods
non-const and the other pointer-setting method const.
This has not been commented on in the online errata list.
Am I missing something?
Is there any reason why set_ptr needs to be non-const?
Many thanks for your help.
Paul Epstein
have a question about the following smart pointer code from this text:
class U_Ptr
{friend class HasPtr;
int* ip;
size_t use;
U_Ptr(int* p): ip(p), use(1) {}
~U_Ptr() { delete ip;}
};
class HasPtr{
public:
void set_ptr(int* p) {ptr -> ip = p;} // THIS IS A NON_CONST METHOD
private:
U_Ptr* ptr;
// Public and private methods and members continue
};
Later in the text, a different implentation of HasPtr is given:
class HasPtr{
public:
HasPtr(const int& p, int i): ptr(new int(p)), val(i) {}
private:
int* ptr;
int val;
public:
void set_ptr_val(int p) const { *ptr = p; } //CONST METHOD
// Public and private methods and members continue
};
As I see it set_ptr and set_ptr_val don't change their class members
and can both legally be labelled const.
Some might choose to make the pointer-setting methods non-const
according to the logic that data is being changed through the pointer
so the set_ptr methods might be said to be conceptually non-const.
It seems very strange to me to make one of the pointer-setting methods
non-const and the other pointer-setting method const.
This has not been commented on in the online errata list.
Am I missing something?
Is there any reason why set_ptr needs to be non-const?
Many thanks for your help.
Paul Epstein