0

Below is the sample class that i have created and all need to create a vector of objects of below class

#include <stdio.h>
#include "myvector.h"
#include <iostream>

class myvector
{
private:
  double *elem;
  int sz;

public:
  myvector()
  {
    std::cout << " In Constructor \n";
  }

 ~myvector()
 {
   std::cout << " In Destructor \n";
   delete[] elem;
 }

 myvector(int s)
 {
   std::cout << " In Param Cons \n";
   elem= new double[s];
 }
 myvector::myvector(const myvector& that)
 {
    this->sz=that.sz;
    this->elem=that.elem;
 }

myvector&  operator=(const myvector& that)
{
  return *this;
}
};

Below is the main function

#include <iostream>
#include "myvector.h"
#include <vector>

int main(int argc, const char * argv[]) {
// insert code here...
 myvector abc(10);
 std::vector<myvector> abc(10,10);
 getchar();
 return 0;
}
myvector abc[10];  works perfectly and creates an array of objects

But as i need to call the parameter constructor for all these objects i have used below

std::vector abc(10,10);

This actually is not creating an array and is failing with the error

vector(16828,0x10013e380) malloc: * error for object 0x100400050: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

And parametric function was not even called 10 times , its called just once

LearningCpp
  • 972
  • 12
  • 29

1 Answers1

1

This is a traditional issue because you are copying objects but you class is not copy-safe.

What happens if you copy your data to another container and it is destroyed? double free. You can't have a copy constructor, it should be = delete.

This will be obvious if you use C++ good practices and use:

std::unique_ptr<double[]> elements;

instead of manual memory management (you are in C++11 now, not in C++03, you shouldn't delete anything explicitly anymore).

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Sure , But this std::vector abc(5,10); still odes not create 5 objects of my vector, it is just calling the parameter constructor once . I am missing something here but can't find out what – LearningCpp Oct 21 '18 at 13:13
  • @LearningCpp It's creating one object which it copies to the other objects. – molbdnilo Oct 21 '18 at 13:16
  • thanks , i never realised its happening and never came across this problem, How was this handled in previous version of c++ ,i.e 90's – LearningCpp Oct 21 '18 at 13:20
  • You would allocate new data in the copy constructor. That's still something you can do, of course. – Matthieu Brucher Oct 21 '18 at 13:33