Re: Modifying non-const object from const function?

Discussion in 'C++' started by Francesco, Aug 31, 2009.

  1. Francesco

    Francesco Guest

    On 31 Ago, 13:05, (Pascal J. Bourguignon)
    wrote:
    > Francesco <> writes:
    > > On 31 Ago, 12:32, "fdm" <> wrote:
    > >> I have a const function where it should be possible to modify an object but
    > >> not the argument:

    >
    > >> void myfun(const int point) const {

    >
    > >> m_Container.push_back(point);

    >
    > >> }

    >
    > >> But I get the error:

    >
    > >> Error 13 error C2662: 'std::vector<_Ty>::push_back' : cannot convert 'this'
    > >> pointer from 'const std::vector<_Ty>' to 'std::vector<_Ty> &'

    >
    > >> The above is a simplified example of a library that I am supposed to modify
    > >> without changing the function declarations. How do I make it possible to
    > >> modify the std::vector m_Container from the above const function?

    >
    > > Hi,
    > > I suppose the solution to your problem could be to declare m_Container
    > > as mutable, but to get better help you should post sufficient code for
    > > us to analyze.

    >
    > > Please have a look to the clc++ FAQhttp://parashift.com/c++-faq-lite/how-to-post.html#faq-5.8

    >
    > However, in this case, manifestly the purpose of that function is to
    > modify this object, so it should not be const.


    I would have suggested just the same, Pascal, except that the OP says
    that the functions' declarations aren't supposed to change.

    I also think that the function posted above doesn't really reflect the
    real code. The error seems to say that the object, whose this function
    should be a member of, is an instance of a class derived from
    std::vector, while the OP says it is directly a std::vector instance.
    I could be completely wrong, of course, that's just my impression
    based on this limited input. It would be good to see the real code.

    By the way, I noticed that the last thread started by fdm didn't see
    the OP's feedback. I hope to be proved wrong once more on this
    subject.

    Best regards,
    Francesco
     
    Francesco, Aug 31, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Fabian Wein
    Replies:
    8
    Views:
    460
    terminator
    Jul 26, 2007
  2. Javier
    Replies:
    2
    Views:
    567
    James Kanze
    Sep 4, 2007
  3. fungus
    Replies:
    13
    Views:
    892
    fungus
    Oct 31, 2008
  4. fdm
    Replies:
    11
    Views:
    796
    Francesco
    Sep 1, 2009
  5. none
    Replies:
    3
    Views:
    3,269
    James Kanze
    May 20, 2010
Loading...

Share This Page