jakob
jakob

Reputation: 157

destructor deletes contents of pointer

I am trying to have an array as part of a class. The array should be the variable size. In my code, the array should be given contents by some function to a variable size and after that treated just as a member of a class. My code isn't running and I was able to boil my problem down to a couple of lines of code.

In this example, I am holding the array in a pointer "dptr" so it can be initialized by a function to variable size and then accessed as a class member.

After I gave the pointer contents in a void I can call it exactly once, after that all I get when accessing it is some kind of weird, almost random, number.

class x 
{
public:
   double* dptr;

void void_()
   {
       double d[] = { 2., 3., 4. };
       dptr = d;
   }
};


int main() 

{
   x x_;
   x_.void_();

   int index = 0;
   std::cout << x_.dptr[index] << std::endl; // works perfectly fine for any index ( outputs 2 )

   std::cout << x_.dptr[index] << std::endl; // outputs something random ( outputs 6.95241e-310 )
}

I guess that after the void ends the destructor of the double "d" is called and the contents the pointer points to are deleted.

Is there some way of solving that problem by, for example, not allowing the destructor to be called?

Upvotes: 0

Views: 72

Answers (2)

Brad
Brad

Reputation: 2320

Nope, you're stuck with using a dynamically allocated pointer and adding a destructor to the class:

class x 
{
public:
   double* dptr;

x()
  {
    dptr = nullptr;
  }
x(const &x) = delete;
operator=(const &x) = delete;

void void_()
   {
       double d[] = new double[3]
       d[0] = 2.;
       d[1] = 3.;
       d[2] = 4.; 
       dptr = d;
   }
 ~x() 
   {
       if(dptr != nullptr) {
          delete[] dptr;
       }
   }
};

But if you're trying to allocate an array in this way to do any real work, please consider using std::vector instead. Then all the internals are handled for you and you don't have to mess with pointers.

Upvotes: -2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

The clean way would be to use a std::vector and initialize the member when the constructor is called:

struct x {
    std::vector<double> d;
    x() : d{2.,3.,4.} {}
};

The way to avoid a descrutor getting called is to dynamically create the array. However, in that case x should to follow the rule of 5.

Upvotes: 4

Related Questions