Advice on proper handling, is it wise?

I do some funky things with pointers, and I worry that I can leave myself open to some problems with pointers:

#include <iostream>

class Vector2
{
private:
 double x;
 double y;

public:
 Vector2(double x, double y)
 {
  this->x = x;
  this->y = y;
 }

 Vector2(double coords[2])
 {
  x = coords[0];
  y = coords[1];
 }

 typedef double * const dArr;
 operator dArr()
 {
  double out[2] = {x, y};
  return out;
 }
};

int main()
{
 double ids[2] = {2.3 ,3.3};
 Vector2 v = ids;
 std::cout << 5 << std::endl;
 double vect[2] = {v[0], v[1]};
 double * const v2 = v;

 std::cout << vect[0] << " " << vect[1] << std::endl;

 while(1) { }

 return 0;
}

In the dArr () function of the operator in the Vector2 class, I am concerned that by returning the pointer, I open up problems where the pointer will not be deleted and this will cause a memory leak. Am I worried correctly, is there a solution to prevent a memory leak in this case? Any suggestions would be greatly appreciated.

Thank.

+3
source share
3 answers

. , new . , undefined.

1: double [2] dPtr():

2 (): x y [2] :

#include <iostream>

class Vector2
{
private:
   double coords_[2];

public:
   Vector2(double x, double y)
   {
      coords_[0] = x;
      coords_[1] = y;
   }

   Vector2(double coords[2])
   {
      coords_[0] = coords[0];
      coords_[1] = coords[1];
   }

   typedef const double* const dArr;
   operator dArr() const
   {
      return coords_;
   }
};

int main()
{
   double ids[2] = {2.3 ,3.3};
   Vector2 v = ids;
   std::cout << 5 << std::endl;
   double vect[2] = {v[0], v[1]};
   const double * const v2 = v;

   std::cout << vect[0] << " " << vect[1] << std::endl;

   while(1) { }

   return 0;
}

const double *, , const. ( , .)

+2

, . : P ... - ( , ), , std::vector.

0

You are better off using a static array container, for example boost::array<double, 2>. Native arrays have terrifying syntax and semantics - if you want to return an array to a container of this type, you can simply return a link to it, as usual.

0
source

Source: https://habr.com/ru/post/1780723/


All Articles