how to avoid const_cast 
Author Message
 how to avoid const_cast

Hi there,

Assume a class A which has a CObList as its data member,
in its "Set" function, we have the following:

void A::SetData(const CObList& srcData)
{
     // m_data is empty at this point
     m_data.AddTail(const_cast<CObList *>&srcData);

Quote:
}

So, m_data makes a copy of srcData and thus does the "set" operation.

Because CObList::AddTail() does not tak const CObList*,
I have to cast the const of srcData away to satisfy the compiler,
as seen in the code.

Why would CObList::AddTail() not take a const CObList* ?
Is there any way other than using const_cast to make the compiler happy?

Thanks in advance.
--
Yan



Sat, 01 Mar 2003 04:05:16 GMT  
 how to avoid const_cast
Hi,

I have always hated the very notion of const_cast! If something is specified
as being constant, then it's done for a reason, and it shouldn't be messed
around with. If problems like yours arise, then it's the fault of the
whoever programmed the function - they should have used const.

Anyway, in your case I don't think the programmer was at fault. The CObList
class has plenty of members to alter elements, so the contained pointers are
NOT const.

You appear to be doing something extremely dodgy. Where is this reference
coming from? How do you know
that the object will continue to live as long as its pointer in the list
does? You should really let the CObList manage the data itself. ie create a
new CObList

m_data.AddTail(new CObList(srcData));

I suggest you take a look at your architecture again,

Jeremy


Quote:

> Hi there,

> Assume a class A which has a CObList as its data member,
> in its "Set" function, we have the following:

> void A::SetData(const CObList& srcData)
> {
>      // m_data is empty at this point
>      m_data.AddTail(const_cast<CObList *>&srcData);
> }

> So, m_data makes a copy of srcData and thus does the "set" operation.

> Because CObList::AddTail() does not tak const CObList*,
> I have to cast the const of srcData away to satisfy the compiler,
> as seen in the code.

> Why would CObList::AddTail() not take a const CObList* ?
> Is there any way other than using const_cast to make the compiler happy?

> Thanks in advance.
> --
> Yan



Sun, 02 Mar 2003 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Error with const_cast<...>, porting from a VC6 project

2. STL string and const_cast

3. const_cast behavior

4. again on const_cast and .c_str()

5. Avoiding memory problems

6. HOW TO AVOID SCREEN CAPTURE?

7. Q: Avoiding name collisions in C89.

8. XML serialization - avoiding serializing an attribute

9. avoid having to use Math.Sqrt for Sqrt()

10. How to avoid user from entering a new row into the datagrid[which already contains rows]

11. avoiding type-conflicting error

12. how to avoid type declaration duplication

 

 
Powered by phpBB® Forum Software