3

我的工作是完全重写一个用于 GIS 矢量数据处理的旧库。主类封装了一组建筑轮廓,并提供了不同的方法来检查数据的一致性。这些检查函数有一个可选参数,允许执行某些过程。

例如:

std::vector<Point> checkIntersections(int process_mode = 0);

此方法测试某些建筑物轮廓是否相交,并返回相交点。但是如果您传递一个非空参数,该方法将修改轮廓以删除交集。

我认为这很糟糕(在调用站点,不熟悉代码库的读者会假设名为 checkSomething 的方法只执行检查而不修改数据),我想改变它。我还想避免代码重复,因为检查和处理方法大多相似。

所以我在想这样的事情:

// a private worker
std::vector<Point> workerIntersections(int process_mode = 0)
{
    // it's the equivalent of the current checkIntersections, it may perform
    // a process depending on process_mode
}


// public interfaces for check and process
std::vector<Point> checkIntersections()  /* const */
{
    workerIntersections(0);
}


std::vector<Point> processIntersections(int process_mode /*I have different process modes*/)
{
    workerIntersections(process_mode);
}

但这迫使我打破 const 的正确性,因为 workerIntersections 是一种非常量方法。

如何分离检查和处理,避免代码重复并保持 const 正确性?

4

2 回答 2

4

就像您已经指出的那样,您的建议将中断const-correctness。这是因为您的建议本质上包括用新的interface而不是redesign内部的代码来包装现有代码。这种方法有严重的局限性,因为它直接受到底层块的影响。

Instead I would suggest you to redesign the existing code and just break the checkIntersections in 2 public methods that you need. The checkIntersections will include the checking part and processIntersections will include the call to checkIntersections and the processing code based on the result of checkIntersections.

于 2012-12-11T14:43:08.503 回答
1

In this particular case, breaking const-correctness shouldn't matter. You (as the author of workerIntersections() know that it will only perform non-const operations if invoked from processIntersections(), a non-const function. Therefore, it's safe to implement checkIntersections() like this:

std::vector<Point> checkIntersections() const
{
    const_cast<TypeOfThis*>(this)->workerIntersections(0);
}

Of course, you must make sure that workerIntersections() really only does const operations when invoked with 0.

const_cast exists in the language for a reason, mainly interoperability with legacy code which ignores const correctness. That's exactly what you're doing, so as long as you do it safely, you're fine using const_cast.

于 2012-12-11T15:10:44.490 回答