vector<>::clear() problem with const data member

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iammilind
    New Member
    • Sep 2006
    • 14

    vector<>::clear() problem with const data member

    In one of my code, I was using vector<> for certain class. In one of my struct, I have 'const' member data. However, vector<>::clear () throws compile error with that:
    =============== =============== =============
    struct Test
    {
    const string Str;
    Test(const string str) : Str(str)
    {}
    };

    struct TestWrapper
    {
    vector<Test> vObj;
    ~TestWrapper()
    {
    // vObj.clear(); // If you remove above comment, it gives following error
    } // However, it works fine with vObj.pop_back()
    };

    Error:
    /usr/lib/gcc/x86_64-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h: In member function `Test& Test::operator= (const Test&)':
    ...
    /usr/lib/gcc/x86_64-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h: 247: error: non-static const member `const std::string Test::Str', can't use default assignment operator =============== =============== =============


    My confusion is why in the 1st place vector<>::clear () should require to use operator =() of class ? Should not it be as easy as pop_back() ?
    (if I overload the assignment and copy constructor, it doesn't give error and works fine.
    Thanks & happy new year !
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    My guess is than since vector requires containing objects to be copyable, it doesn't matter that some functions compile and some doesn't if this condition isn't met - it depends on internal implementation.

    Comment

    Working...