如何在 C++ 中删除静态对象

how to delete a static object in c++

本文关键字:删除 静态 对象 C++      更新时间:2023-10-16

我正在尝试构建简单的画家(即点,线,圆...等)过剩。每行必须有两个Point类型的点,因此每次用户输入鼠标左键时,都会执行所选命令。为了画一条线,我需要跟踪用户点击鼠标的次数,所以我就是这样做的。

        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++;
            }

我使用 std::vector 只是为了使用clear(),以便我可以删除我需要它是静态startPoint。我的问题是有没有办法通过使用vector在不制作更多线条的情况下破坏物体?我试图调用析构函数,但它没有帮助。

您可以使用

unique_ptr<Point> . 然后你可以使用reset来设置或销毁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));
}

你的代码很好。如果您担心行数,那么这是一个较短的版本:

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();
    }
}

但请注意,使用更少的行只有在这提高了可读性的情况下才是一件好事。相反,如果理解代码变得更加困难,那么这是一个坏主意。

大多数代码只写一次,但读取多次......写作时节省时间没什么大不了的。

在我看来,在这种特定情况下,这个较短的版本更容易理解,但您的里程可能会有所不同。

这是像std::optional<Point>这样的事情会很好的时候之一。

但是关于破坏和重建部分,放置新位置在这里可能会有所帮助:

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++;
}