简体   繁体   中英

Correct use of const c++

I have this sample code ( below ), example1() method works with no problem, example2() is similar but I must force const_char to make it compile, although I consider as example1() method is not needed, example2() would be not needed either.

My question is, how can I modify add() method to make both compile or how must I correctly call buffer.add() in example2() without forcing const_cast? add() method is not modifying item, so const_cast is unnecessary. Which is the correct or suitable form?

Here's the sample code:

template <class Item>
class Buffer
{
public:
    Item *      _pItems;
    int         _nItems;
    // ... constructor / destructors etc
    void    add( const Item & item ) // or maybe Item const & item
    {
        _pItems[_nItems++] = item;
    }
};
class MyClass
{
public:
    // data
};
void    example1( const MyClass & item )
{
    Buffer<MyClass>        buffer;
    buffer.add( item );  // WORKS, no problem
}
void    example2( const MyClass & item )
{
    Buffer<MyClass *>        buffer; // NOW with pointers to MyClass
    //buffer.add( item );  // ERROR: 'Buffer<Item>::add' : cannot convert parameter 1 from 'const MyClass' to 'MyClass *const &'
    buffer.add( const_cast<MyClass *>( &item ) );  // forcing const_cast WORKS
}

You should do something like :

Buffer<MyClass const*> 

because &item on a const MyClass is a Myclass const* not a MyClass*

Your Buffer class template can be considered to be correct and it is your example2 function which is incorrect. I'll proceed on that basis.

In example1 , the function has a const reference parameter to an instance of a MyClass . The add method of Buffer then makes a copy of the value of the instance, placing it in its own memory buffer (I hope Buffer is keeping track of all of this memory). Therefore the fact that example takes a const reference is irrelevant to Buffer since a copy of the value is made.

In example2 , the add method of Buffer is taking a copy of the pointer to the instance of MyClass and storing that in its own memory buffer. In example2 you have instantiated Buffer as holding non-const pointers to MyClass , so that is what you should be giving it, so example2 should be:

void example2( MyClass & item )
{
    Buffer<MyClass *> buffer; // NOW with pointers to MyClass
    buffer.add( &item );
}

Now, you must be aware that if buffer were to be used, the item must remain fixed in memory until you've finished with it. Whereas in example1 , the items can go away since you've safely stored copies in buffer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM