0

I have the following simple class

class VecDyn {
 public:
  double *v = nullptr;
  int n;

  VecDyn(){}

  VecDyn(int n){
    resize(n);
  }

  ~VecDyn() {
    delete[] v;
  }

  void resize(int size) {
    delete[] v;
    v = new double[size];
    n = size;
  }
}

Then when I create an object in main(). It works fine. But when I create std::vector like following

int main() {
  std::vector<VecDyn> testVec(5, VecDyn(3));
}

This gives me a segfault. Can anyone tell me what I am doing wrong here? Thank you in advance ;)

ultrafrog
  • 183
  • 6
  • 3
    The code violates the [rule of three](http://en.cppreference.com/w/cpp/language/rule_of_three). – HolyBlackCat Nov 02 '17 at 21:47
  • 2
    You don't need `vector` to show your error: `int main() { VecDyn v(1); VecDyn v2 = v; }` -- Boom you're dead. Operations like this is what vector is doing internally. – PaulMcKenzie Nov 02 '17 at 21:48
  • 1
    One rule of thumb, is that if you have a pointer in your object that you need to `delete` on destruction or create with `new` on construction (or both) that you need a copy constructor and assignment operator. The rule of three. In this case, you should be using `::std::unique_ptr` anyway instead of a bare pointer. Doing that would've saved you writing the destructor. – Omnifarious Nov 02 '17 at 21:51
  • double *v = nullptr; I think the problem is here... – Samer Nov 02 '17 at 21:59
  • Thank you very much. copy constructor fixed the issue. I am not sure how I can use unique_ptr here tho. Omnifarious, can you explain how I should write resize with unique_ptr? – ultrafrog Nov 02 '17 at 22:18
  • std::unique_ptr is not what I want because I need an array... How can I deal with this case? – ultrafrog Nov 02 '17 at 22:40

0 Answers0