Home > Software design >  C Class variable deletion and public variables
C Class variable deletion and public variables

Time:06-09

I'm trying to work a bit with classes and get the gist of it. Currently I'm sitting on a few problems. First, is it necessary to delete variables defined within one of the class functions for memory management? Ex:

void DetectFood(std::vector<Food> foods)
{
    for (int i = 0; i<foods.size(); i  ){
        int *xDist = new int;
        int *yDist = new int;
        int *dist = new int;
        *xDist = abs((int)x-foods[i].x);
        *yDist = abs((int)y-foods[i].y);
        *dist = sqrt(pow(*xDist, 2)   pow(*yDist, 2));
        if (*dist<=50)
        {
            std::cout<<"Close "<<*dist<<"\n";
        }

        delete xDist;
        delete yDist;
        delete dist;
        xDist = NULL;
        yDist = NULL;
        dist = NULL;

    }
}

The last part with delete and NULL is there to not create a lot of unnecessary variables. I was just wondering if this already is done automatically, or if it's done wrong by me?

Second, is there a easy way to interact with variables outside of the class? For instance, I have in my main loop two vector variables, one for "Food" and one for "Animals" (both classes). I need to remove one of the items from this vector within a function in one of the classes (eat one of the "Food"'s). Is this possible, and if so how? Thanks for any help in advance:)

Edit: I know the code segment isn't optimized, that was not what I was going for. It was mostly just to test this function, and to demonstrate what I was talking about. And I know how to shorten it, don't worry

CodePudding user response:

I'm taking the unconventional (and often frowned upon) step of giving you the solution as I would code it. Presumably x and y are globals or class member variables.

#include <cmath>
#include <iostream>
#include <vector>
void detectFood(const std::vector<Food>& foods)
{
    for (auto&& food : foods){
        if (auto dist = std::hypot(x - it.x, y - it.y); dist <= 50){
            std::cout << "Close "<< dist <<"\n";
        }
    }
}

Are the casts (int)x and (int)y intended? They might have a truncating or even possible overflow effects depending on the type. I've left them out in my answer.

I won't offer further explanation beyond offering up a few tips: (i) use automatic storage duration if possible (ii) use C standard library functions if possible. (iii) I've used std::hypot for its numerical stability; a performance price is paid there but the std::cout call will be orders of magnitude slower. If you roll your own version then x * x is preferable to std::pow(x, 2). (iv) pass large objects by const reference rather than by value.

  • Related