2021年5月4日星期二

Convert piece of code to dynamic allocated version

I want to use the result of TranslatePolygon in //*, storing its returned value into another variable in the function TranslateConformedReferenceElement.

In code I get the following warning at //**

"warning: reference to stack memory associated with local variable 'translatedPolygon' returned"

I know The referred value dies when the function call is over, but still Is there a way to fix it and at the same time keep the return type a Polygon& in order to save memory? How can I convert the code to store objects in the heap? When I change Polygon translatedPolygon = Polygon(); to Polygon* translatedPolygon = new Polygon(); I get a bunch of errors that I can't fix

ReferenceElement Mesh::TranslateConformedReferenceElement(double xTranslation, double yTranslation )  {         Polygon translatedPolygon = TranslatePolygon(_conformedReferenceElementPolygon, xTranslation, yTranslation);//*      //some code      return refEl;  }    Polygon& Mesh::TranslatePolygon(const Polygon& polygon, double xTranslation, double yTranslation)   {      Polygon translatedPolygon = Polygon();      const vector<Point>& initialVertices = polygon.getVertices();      for (vector<Point>::const_iterator it = initialVertices.begin(); it != initialVertices.end(); it++)      {          Point initialVertex = Point(it->getCoordinates());          Point translation =  Point(xTranslation, yTranslation);          Point TranslatedVertex = initialVertex + translation;          translatedPolygon.appendVertex(TranslatedVertex);            }                    return translatedPolygon;  //**             }  
https://stackoverflow.com/questions/67393761/convert-piece-of-code-to-dynamic-allocated-version May 05, 2021 at 08:28AM

没有评论:

发表评论