如何在 C++ 中删除静态对象
how to delete a static object in c++
我正在尝试构建简单的画家(即点,线,圆...等)过剩。每行必须有两个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++;
}
相关文章:
- 我们可以删除链表中静态内存中的节点吗
- 当C++中需要自动删除时,这是静态的正确用法吗?
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何在C++中删除静态数组?
- 如果我想链接静态库并删除未使用的符号.txt我应该如何处理 Cmakelist
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 为什么将鼠标悬停在静态 Win32 控件上会增加内存并删除我的 GUI?
- 从静态库中去除/删除调试符号和存档名称
- 静态成员放置删除签名
- 模板类自动注册,vs 2017编译器删除静态成员
- 您可以删除本地静态变量吗?
- 删除父类时,方法局部静态变量会发生什么情况
- 删除静态/动态指针后无法重新分配内存
- 如何删除静态互斥对象
- VC++链接器删除静态库的间接依赖项
- 在卸载 DLL 期间删除静态对象时退出线程会导致死锁
- 如何在 C++ 中删除静态对象
- 如何避免 C++ 编译器优化器删除静态变量代码
- c++删除静态数据
- 抛出异常时是删除静态对象,还是只删除本地对象