2
class MyVect:private std::vector<std::vector<std::string> >
{
    typedef std::vector<std::vector<std::string> > super;

public:
///When this is commented out -- No Seg Fault//////////////
    std::vector<std::string>& operator[](int plt)
    {
        return static_cast<super>(*this)[(int)plt];
    }
///////////////////////////////////////////////////////////

    MyVect()
    {
        this->resize(4); // this works fine
        for (int i = 0; i<4;i++)
        {
            (*this)[i].resize(3); // I think this doesn't 
        }
        (*this)[0][0] = "hello";
    }
};

The above code, causes a seg fault and I can't figure out what is wrong?

*** glibc detected *** invalid fastbin entry (free): 0x09267040
T.C.
  • 133,968
  • 17
  • 288
  • 421
Kam
  • 5,878
  • 10
  • 53
  • 97
  • 2
    @BryanChen Please don't mislead. There is no such rule. – SwiftMango Feb 17 '16 at 04:48
  • 3
    [Inherit from `std::vector` is a bad idea](http://stackoverflow.com/questions/6806173/subclass-inherit-standard-containers/7110262#7110262). – Bryan Chen Feb 17 '16 at 04:51
  • 1
    @BryanChen Much of the arguments in there don't apply to private inheritance. – T.C. Feb 17 '16 at 04:54
  • 1
    @BryanChen Well the most critical reason in that link you mentioned is that the destructor of std::vector is not virtual. However, since I know I will never use an std::vector pointer to reference my object, I don't see anything wrong with it. – Kam Feb 17 '16 at 04:54

1 Answers1

6

static_cast<super>(*this) creates a temporary and slices *this.

You want static_cast<super&>(*this).

T.C.
  • 133,968
  • 17
  • 288
  • 421