-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
First stage to memory rework #6
base: master
Are you sure you want to change the base?
Conversation
WalkthroughThe changes involve refactoring memory management across multiple source files by replacing raw pointers with smart pointers and stack-allocated objects. This transition enhances memory safety by automating resource management and eliminating the need for manual deallocation. Additionally, new methods are introduced in the Changes
Sequence Diagram(s)sequenceDiagram
participant A as User
participant B as FilletPoint
participant C as ChFi2d_FilletAlgo
A->>C: Call FillDiff()
C->>B: Create FilletPoint with make_unique
B->>B: Reset parameters
B->>C: Return FilletPoint
C->>A: Return result
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Outside diff range and nitpick comments (7)
src/ChFi2d/ChFi2d_FilletAlgo.hxx (2)
149-151
: LGTM! Consider enhancing the documentation.The addition of the
Reset
method is a good improvement to theFilletPoint
class, allowing for object reuse. This can potentially improve performance in scenarios whereFilletPoint
objects are frequently reset.Consider adding a brief explanation of what the "default version" entails in the method comment. For example:
//! Resets a point to the default version (e.g., clears all computed values and sets the parameter) void Reset(const Standard_Real theParam);This would provide more clarity to users of the class.
197-200
: LGTM! Consider enhancing documentation and method name for clarity.The addition of the
Copy
method provides a useful way to partially copyFilletPoint
objects. This can be beneficial for performance in scenarios where only specific attributes need to be copied.
- Consider renaming the method to
PartialCopy
orCopyEssentialAttributes
to make it immediately clear that this is not a full copy.- Enhance the method comment to explain why only these specific attributes are copied and in what scenarios this partial copy is useful.
- Consider adding a
const
qualifier to the method to indicate that it doesn't modify the current object.Here's an example of how you might implement these suggestions:
//! Copies essential attributes (myParam, myV, myD, myValid) to the given point. //! This partial copy is useful for [explain specific use case]. //! Note: Other attributes are not copied and retain their default values. void PartialCopy(FilletPoint& thePoint) const;These changes would improve the clarity and usability of the method.
src/BinLDrivers/BinLDrivers_DocumentStorageDriver.cxx (2)
129-130
: Great improvement in memory managementThe transition from raw pointers to
std::unique_ptr
significantly enhances memory safety:
- Automatic resource management prevents potential memory leaks.
- Usage of
opencascade::make_unique
ensures exception safety during object construction.This change aligns well with modern C++ best practices.
Consider using
auto
for type deduction to improve readability:-std::unique_ptr<BinLDrivers_DocumentSection> aShapesSection; +auto aShapesSection = std::unique_ptr<BinLDrivers_DocumentSection>(); -aShapesSection = opencascade::make_unique<BinLDrivers_DocumentSection> (SHAPESECTION_POS, - Standard_False); +aShapesSection = opencascade::make_unique<BinLDrivers_DocumentSection>(SHAPESECTION_POS, + Standard_False);Also applies to: 135-136
Line range hint
1-1000
: Summary: Improved memory safety and code organizationThe changes in this file represent a significant improvement in memory management and code organization:
- Transition from raw pointers to
std::unique_ptr
for automatic resource management.- Use of
opencascade::make_unique
for exception-safe object construction.- Proper deallocation using
reset()
instead of manual deletion.- Improved header organization and inclusion.
These modifications align with modern C++ best practices and enhance the overall quality and safety of the code without altering its core functionality. This refactoring is a positive step towards modernizing the codebase and reducing the risk of memory-related issues.
Consider extending this approach to other parts of the codebase:
- Gradually replace raw pointers with smart pointers where appropriate.
- Use RAII principles consistently across the project.
- Implement a code review checklist to ensure these best practices are followed in future changes.
src/Approx/Approx_CurveOnSurface.cxx (2)
449-449
: LGTM: Improved memory management with smart pointersThe replacement of raw pointers with
std::unique_ptr
and the use ofopencascade::make_unique
for initialization significantly improves memory safety and exception safety in this code. These changes eliminate the need for manual memory management and reduce the risk of memory leaks.Consider removing the explicit
aCutTool.reset()
call at line 486, as it's redundant. Theunique_ptr
will automatically clean up when it goes out of scope at the end of the function.Also applies to: 455-455, 466-466, 477-477, 486-486
Line range hint
449-486
: Excellent refactoring for improved memory managementThe changes in this section significantly enhance the memory management of the
Perform
function. By replacing raw pointers withstd::unique_ptr
and usingopencascade::make_unique
for object creation, the code becomes more robust against memory leaks and exception-related issues. These modifications align well with modern C++ best practices and contribute to overall code quality and safety.Consider applying similar smart pointer patterns consistently across the codebase to further improve memory safety and reduce the risk of resource leaks.
src/ChFi2d/ChFi2d_FilletAlgo.cxx (1)
283-289
: Replace magic number999.
with a named constantTo improve code readability and maintainability, consider defining the magic number
999.
as a named constant or provide a comment explaining its significance.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- src/Approx/Approx_CurveOnSurface.cxx (4 hunks)
- src/BSplCLib/BSplCLib.cxx (10 hunks)
- src/BinLDrivers/BinLDrivers_DocumentStorageDriver.cxx (3 hunks)
- src/Bisector/Bisector_Inter.cxx (4 hunks)
- src/ChFi2d/ChFi2d_FilletAlgo.cxx (6 hunks)
- src/ChFi2d/ChFi2d_FilletAlgo.hxx (2 hunks)
- src/TopOpeBRep/TopOpeBRep_FacesIntersector.cxx (1 hunks)
🔇 Additional comments (17)
src/ChFi2d/ChFi2d_FilletAlgo.hxx (1)
Line range hint
1-200
: Overall, the changes improve theFilletPoint
class functionality.The additions of the
Reset
andCopy
methods to theFilletPoint
class are positive improvements that enhance the flexibility and potential performance of the code. These methods allow for more efficient reuse and partial copying ofFilletPoint
objects, which could be particularly beneficial in performance-critical scenarios.The changes are consistent with the existing code style and conventions, maintaining the overall quality and readability of the codebase. The minor suggestions provided for improving documentation and naming will further enhance the clarity and usability of these new methods.
These changes align well with the PR objective of refactoring memory management, as they provide more control over object lifecycle and data copying, which can lead to more efficient memory usage.
src/Bisector/Bisector_Inter.cxx (5)
102-105
: Excellent use of NCollection_Array1 for improved memory managementThe replacement of dynamically allocated arrays with
NCollection_Array1
is a positive change. This approach enhances memory safety by automating resource management and eliminating the need for manual deallocation. The array sizes are correctly set based on the number of intervals plus one, ensuring proper allocation for all elements.
135-136
: Correct usage of SetValues for anArrayOfDomainBis1The
SetValues
method is correctly used to populate theanArrayOfDomainBis1
array. The parameters and tolerances are passed appropriately, maintaining the original functionality while utilizing the newNCollection_Array1
data structure.
143-143
: Correct assignment of curve values to anArrayOfCurveBis1The code correctly assigns values to
anArrayOfCurveBis1
for different cases. It properly handles the extended parts by constructing a segment (line 143) and the regular case by directly assigningBis1
(line 146). This preserves the original logic while using the newNCollection_Array1
data structure.Also applies to: 146-146
197-198
: Correct usage of NCollection_Array1 objects in SinglePerform callThe
SinglePerform
method is correctly called with the newNCollection_Array1
objects. The indexing of the arrays (IB1
andIB2
) is appropriate, completing the transition from dynamically allocated arrays toNCollection_Array1
. This change maintains the original functionality while improving memory management.
Line range hint
1-424
: Summary of changes: Improved memory management in Bisector_InterThe changes in this file successfully refactor the memory management by replacing dynamically allocated arrays with
NCollection_Array1
. This transition enhances memory safety by automating resource management and eliminating the need for manual deallocation. The functionality of the code has been preserved while improving its robustness and aligning with modern C++ practices.Key improvements:
- Replaced raw pointers with
NCollection_Array1
for curves and domains.- Eliminated manual memory deallocation, reducing the risk of memory leaks.
- Maintained the original logic and functionality while using safer data structures.
One minor issue was identified: a typo in a condition checking the number of intervals for Bis2. This should be addressed for consistency and correctness.
Overall, these changes significantly improve the code quality and align well with the PR objective of refactoring memory management.
src/BinLDrivers/BinLDrivers_DocumentStorageDriver.cxx (3)
16-16
: LGTM: Improved header managementThe changes to the header inclusions are well-structured:
- Including the class's own header file at the top is a good practice.
- Splitting the Message headers improves modularity.
- Adding Standard_MemoryUtils.hxx aligns with the goal of improving memory management.
These modifications enhance code organization and prepare for the memory management improvements.
Also applies to: 26-27, 30-30
168-168
: Correct usage of unique_ptrThe replacement of manual deletion with
reset()
is the proper way to handle memory deallocation forunique_ptr
. This change:
- Ensures consistent memory management throughout the lifecycle of
aShapesSection
.- Improves exception safety.
- Aligns with modern C++ best practices.
Line range hint
16-168
: Verify impact on the codebaseThe changes improve memory management without altering the class's public API or core logic. This should result in:
- No negative impact on existing code interacting with this class.
- Potential prevention of memory-related issues in the future.
To ensure there are no unintended consequences:
Run the following script to check for any changes in the public API or usage of this class:
src/Approx/Approx_CurveOnSurface.cxx (2)
40-40
: LGTM: Inclusion of memory utilities headerThe addition of
Standard_MemoryUtils.hxx
is appropriate for the upcoming changes related to smart pointer usage, which will improve memory management in the code.
484-484
: LGTM: Updated constructor callThe change from
*CutTool
to*aCutTool
in theAdvApprox_ApproxAFunction
constructor call is correct and consistent with the switch to using a smart pointer. This ensures that the underlyingAdvApprox_Cutting
object is properly passed to the constructor.src/TopOpeBRep/TopOpeBRep_FacesIntersector.cxx (1)
400-409
: Improved memory safety, but verify correctness and performanceThe changes replace dynamic memory allocation with stack allocation for
IntPatch_LineConstructor
objects, which improves memory safety by eliminating manual memory management. This is a positive change that reduces the risk of memory leaks and improves code maintainability.However, please consider the following points:
Ensure that the new implementation correctly handles all cases that the old one did, especially if there were any specific reasons for using dynamic allocation before.
Be aware of potential stack overflow issues if
IntPatch_LineConstructor
is a large object and this method is called with deep recursion or in a constrained stack environment.Verify that the loop logic (which is not shown in this diff) has been appropriately adjusted to work with the new stack-allocated object instead of the previous array of pointers.
To ensure the changes don't introduce any regressions, please run the following verification:
✅ Verification successful
Memory management improvements verified successfully
The removal of
malloc
andfree
insrc/TopOpeBRep/TopOpeBRep_FacesIntersector.cxx
has been confirmed, ensuring that dynamic memory allocation has been replaced with stack allocation forIntPatch_LineConstructor
. Additionally, the loop logic involvingaLineConstructor
remains correct and functions as intended.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining uses of malloc or free in this file rg --type cpp "(malloc|free)\(" src/TopOpeBRep/TopOpeBRep_FacesIntersector.cxx # Check for any changes in the loop logic that uses aLineConstructor rg --type cpp -A 10 "aLineConstructor" src/TopOpeBRep/TopOpeBRep_FacesIntersector.cxxLength of output: 869
src/ChFi2d/ChFi2d_FilletAlgo.cxx (5)
35-35
: Confirmation of necessary include directiveThe inclusion of
<Standard_MemoryUtils.hxx>
is necessary for the use ofopencascade::make_unique
, which enhances memory management.
329-330
: Use ofstd::unique_ptr
foraLeft
andaRight
enhances memory safetyTransitioning to smart pointers eliminates manual memory management and reduces the risk of memory leaks.
341-343
: Consistent use of smart pointers foraRight
Using
std::unique_ptr
foraRight
aligns with modern C++ practices and ensures proper resource management.
345-346
: Appropriate use of raw pointers from smart pointersPassing raw pointers obtained via
.get()
fromstd::unique_ptr
to functions expecting raw pointers is appropriate in this context.
645-658
: Addition ofFilletPoint::Reset
methodThe new
Reset
method correctly initializesmyParam
, resetsmyParam2
to zero, and clears internal data structures. This enhances object reusability and maintains consistent state.
anArrayOfDomainBis2 [IB2].SetValues(PMin,UMin,D2.FirstTolerance(), | ||
PMax,UMax,D2.LastTolerance()); | ||
|
||
if ((IB2 == 1 && Bis2->IsExtendAtStart()) || | ||
(IB2 == Bis1->NbIntervals() && Bis2->IsExtendAtEnd()) ){ | ||
//-------------------------------------------------------- | ||
// Part corresponding to an extension is a segment. | ||
//-------------------------------------------------------- | ||
SBis2 [IB2] = ConstructSegment (PMin,PMax,UMin,UMax); | ||
anArrayOfCurveBis2 [IB2] = ConstructSegment (PMin,PMax,UMin,UMax); | ||
} | ||
else { | ||
SBis2 [IB2] = Bis2; | ||
anArrayOfCurveBis2 [IB2] = Bis2; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct assignment of values to anArrayOfDomainBis2 and anArrayOfCurveBis2 with a minor typo
The code correctly assigns values to anArrayOfDomainBis2
and anArrayOfCurveBis2
, consistent with the changes made for Bis1. The usage of NCollection_Array1
is appropriate and maintains the original functionality.
However, there's a minor typo in the condition on line 180:
- (IB2 == Bis1->NbIntervals() && Bis2->IsExtendAtEnd()) ){
+ (IB2 == Bis2->NbIntervals() && Bis2->IsExtendAtEnd()) ){
This should be corrected to use Bis2
instead of Bis1
for consistency and correctness.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
anArrayOfDomainBis2 [IB2].SetValues(PMin,UMin,D2.FirstTolerance(), | |
PMax,UMax,D2.LastTolerance()); | |
if ((IB2 == 1 && Bis2->IsExtendAtStart()) || | |
(IB2 == Bis1->NbIntervals() && Bis2->IsExtendAtEnd()) ){ | |
//-------------------------------------------------------- | |
// Part corresponding to an extension is a segment. | |
//-------------------------------------------------------- | |
SBis2 [IB2] = ConstructSegment (PMin,PMax,UMin,UMax); | |
anArrayOfCurveBis2 [IB2] = ConstructSegment (PMin,PMax,UMin,UMax); | |
} | |
else { | |
SBis2 [IB2] = Bis2; | |
anArrayOfCurveBis2 [IB2] = Bis2; | |
anArrayOfDomainBis2 [IB2].SetValues(PMin,UMin,D2.FirstTolerance(), | |
PMax,UMax,D2.LastTolerance()); | |
if ((IB2 == 1 && Bis2->IsExtendAtStart()) || | |
(IB2 == Bis2->NbIntervals() && Bis2->IsExtendAtEnd()) ){ | |
//-------------------------------------------------------- | |
// Part corresponding to an extension is a segment. | |
//-------------------------------------------------------- | |
anArrayOfCurveBis2 [IB2] = ConstructSegment (PMin,PMax,UMin,UMax); | |
} | |
else { | |
anArrayOfCurveBis2 [IB2] = Bis2; |
auto aPoint1 = opencascade::make_unique<FilletPoint> (theLeft->getParam()); | ||
theLeft->Copy (aPoint1.get()); | ||
auto aPoint2 = opencascade::make_unique<FilletPoint> (theParameter); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct argument type in Copy
method call
The Copy
method expects a reference to FilletPoint
, but aPoint1.get()
returns a pointer. Please dereference the pointer when calling the method:
theLeft->Copy(*aPoint1);
//======================================================================= | ||
//function : Copy | ||
//purpose : | ||
//======================================================================= | ||
FilletPoint* FilletPoint::Copy() | ||
{ | ||
FilletPoint* aCopy = new FilletPoint(myParam); | ||
Standard_Integer a; | ||
for(a = 1; a <= myV.Length(); a++) | ||
{ | ||
aCopy->myV.Append(myV.Value(a)); | ||
aCopy->myD.Append(myD.Value(a)); | ||
aCopy->myValid.Append(myValid.Value(a)); | ||
} | ||
Copy(*aCopy); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Undeclared variable aCopy
in FilletPoint::Copy()
The variable aCopy
is used without declaration, leading to a compilation error. Please declare aCopy
before using it:
FilletPoint* aCopy = new FilletPoint(myParam);
Copy(*aCopy);
return aCopy;
void FilletPoint::Copy (FilletPoint& thePoint) | ||
{ | ||
thePoint.myV.Assign(myV); | ||
thePoint.myD.Assign(myD); | ||
thePoint.myValid.Assign(myValid); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure all relevant member variables are copied in FilletPoint::Copy
The Copy
method copies myV
, myD
, and myValid
, but does not copy myParam
, myParam2
, and myNear
. Consider copying these members as well to ensure a complete duplication of the object's state.
NCollection_Array1<Standard_Real> knots (0, 2 * Degree); | ||
NCollection_Array1<Standard_Real> poles (0, (2 * Degree + 1) * Dimension); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incorrect use of ChangeFirst()
when a pointer is expected
The method ChangeFirst()
of NCollection_Array1
returns a reference to the first element, not a pointer to the internal data array. In the code, you are passing knots.ChangeFirst()
and poles.ChangeFirst()
to functions that expect a pointer to the data array (Standard_Real*
). This may lead to incorrect behavior or compilation errors.
To obtain a pointer to the internal data, you should take the address of the first element using &knots.ChangeValue(knots.Lower())
or use knots.ChangeData()
if available.
Apply the following changes to fix the issue:
- NCollection_Array1<Standard_Real> knots (0, 2 * Degree);
- NCollection_Array1<Standard_Real> poles (0, (2 * Degree + 1) * Dimension);
...
- BuildKnots(Degree, curnk, Periodic, nknots, &nmults, knots.ChangeFirst());
+ BuildKnots(Degree, curnk, Periodic, nknots, &nmults, &knots.ChangeValue(knots.Lower()));
...
- BuildBoor(index, length, Dimension, npoles, poles.ChangeFirst());
+ BuildBoor(index, length, Dimension, npoles, &poles.ChangeValue(poles.Lower()));
- BoorScheme(u, Degree, knots.ChangeFirst(), Dimension, poles.ChangeFirst(), depth, length);
+ BoorScheme(u, Degree, &knots.ChangeValue(knots.Lower()), Dimension, &poles.ChangeValue(poles.Lower()), depth, length);
...
- GetPole(i, length, depth, Dimension, poles.ChangeFirst(), np, ThePoles);
+ GetPole(i, length, depth, Dimension, &poles.ChangeValue(poles.Lower()), np, ThePoles);
...
- BuildKnots(Degree, curnk, Periodic, NewKnots, &NewMults, knots.ChangeFirst());
+ BuildKnots(Degree, curnk, Periodic, NewKnots, &NewMults, &knots.ChangeValue(knots.Lower()));
...
- BuildBoor(0, length, Dimension, npoles, poles.ChangeFirst());
+ BuildBoor(0, length, Dimension, npoles, &poles.ChangeValue(poles.Lower()));
- BoorScheme(NewKnots(curnk), Degree, knots.ChangeFirst(), Dimension, poles.ChangeFirst(), depth, length);
+ BoorScheme(NewKnots(curnk), Degree, &knots.ChangeValue(knots.Lower()), Dimension, &poles.ChangeValue(poles.Lower()), depth, length);
...
- GetPole(i, length, depth, Dimension, poles.ChangeFirst(), np, NewPoles);
+ GetPole(i, length, depth, Dimension, &poles.ChangeValue(poles.Lower()), np, NewPoles);
...
- NCollection_Array1<Standard_Real> knots (0, 4 * Degree);
- NCollection_Array1<Standard_Real> poles (0, (2 * Degree + 1) * Dimension);
...
- BSplCLib::BuildKnots(Degree, TheIndex-1, Periodic, Knots, &Mults, knots.ChangeFirst());
+ BSplCLib::BuildKnots(Degree, TheIndex-1, Periodic, Knots, &Mults, &knots.ChangeValue(knots.Lower()));
...
- Standard_Boolean result = AntiBoorScheme(Knots(TheIndex), Degree, knots.ChangeFirst(),
- Dimension, poles.ChangeFirst(),
- depth, length, Tolerance);
+ Standard_Boolean result = AntiBoorScheme(Knots(TheIndex), Degree, &knots.ChangeValue(knots.Lower()),
+ Dimension, &poles.ChangeValue(poles.Lower()),
+ depth, length, Tolerance);
Also applies to: 2019-2019, 2035-2036, 2047-2047, 2091-2091, 2095-2096, 2106-2106, 2111-2111, 2164-2165, 2174-2174, 2208-2209
Summary by CodeRabbit
New Features
FilletPoint
class for resetting and copying point data, enhancing functionality.Bug Fixes
Refactor