How to remove a static object in C ++
I am trying to create a simple artist (i.e. points, lines, circles ... etc) in oversaturation. Each line must have two dots of type Point
, so every time the user enters the left mouse button, the selected command is executed. For drawing a line, I need to track how many times the user clicks on the mouse, so this is what I did
if ( command == 1 ){ // drawing a line
static int count(0); // track click no.
static std::vector<Point> p;
//static Point startPoint(mouseX, mouseY);
p.push_back(Point(mouseX, mouseY));
if ( count == 1 ){
Point endPoint(mouseX, mouseY);
Point startPoint = p[0];
shapes->addLine(Line(startPoint, endPoint));
count = 0;
p.clear();
}else{
count++;
}
I std::vector
only use clear()
to delete startPoint
, which I need to be static. My question is, is there a way to destroy the object without making more lines using vector
? I tried to call the destructor but it didn't help.
source to share
You can use unique_ptr<Point>
. Then you can use reset
to install or destroy Point
:
static std::unique_ptr<Point> startPoint;
if (startPoint){
Point endPoint(mouseX, mouseY);
shapes->addLine({*startPoint, endPoint});
startPoint.reset();
} else {
startPoint.reset(new Point(mouseX, mouseY));
}
source to share
Your code is fine. If you're worried about the number of lines, this is the shorter version:
if ( command == 1 ){ // drawing a line
static std::vector<Point> p;
p.push_back(Point(mouseX, mouseY));
if (p.size() == 2){
shapes->addLine(Line(p[0], p[1]));
p.clear();
}
}
Note that using smaller lines is only a good thing if it improves readability. If it instead becomes harder to understand the code, then this is a bad idea.
Most code is only written once, but read many times ... saving time when there isn't much to write.
In this particular case, in my opinion, this shorter version is easier to understand, but your mileage may change.
source to share
This is one of those times where something seems std::optional<Point>
to be fine.
But regarding the destruction and reconstruction part, the placement might be useful here:
static int count(0);
// ('aligned_storage' requires C++11 and '#include <type_traits>')
static std::aligned_storage<sizeof(Point), alignof(Point)>::type startPointBuffer;
Point& startPoint = *static_cast<Point*>(static_cast<void*>(&startPointBuffer));
if (count == 1) {
Point endPoint(mouseX, mouseY);
shapes->addLine(Line(startPoint, endPoint));
count = 0;
startPoint.~Point();
} else {
new (&startPoint) Point(mouseX, mouseY);
count++;
}
source to share