6

我目前正在尝试通过引入智能指针的使用来修复我们代码库中的一些弱点。代码库非常庞大,并且像一只吃了一对多咖啡的蜘蛛一样相互关联。

我想知道人们是否尝试过以前的方法以及他们的方法是什么。

我的第一步是 typedef 类,如下所示。

#ifndef USE_SMART_POINTERS
    #define USE_SMART_POINTERS 0
#endif

#if USE_SMART_POINTERS == 1
    #include <boost/smart_ptr.hpp>
#endif


namespace ProductX
{
    // forward decleration
    class CTObject;


    //typedefs
    #if USE_SMART_POINTERS == 1
        typedef boost::shared_ptr<CTObject> CTObjectPtr;
    #else
        typedef CTObject* CObjectPtr;
    #endif
}

现在我意识到这将导致大量的编译区域,比如

CTObjectPtr i = NULL;

启用智能指针时将完全停止。

我想知道在这个早期阶段我是否可以做些什么来减少编译错误的数量,还是我怀疑只是根据具体情况进行处理。

干杯丰富

4

4 回答 4

9

Don't do this: the typedefs I mean.

Presumably the old code has at least some delete calls in it? Which would certainly fail in the case of a smart pointer.

Smart pointer certain things or not, i.e. chase a specific instance through the code base. Make it work, then move on. Good Luck!

于 2010-02-24T16:26:56.313 回答
5

Instead of trying to introduce smart pointers everywhere you could use the Boehm-Demers-Weiser garbage collector and leave your code base intact.

It will also take care of cyclic references.

于 2010-02-24T16:34:02.020 回答
3

There is no easy way to do this. As you've found out, boost::shared_ptrs and standard pointers are not interchangeable. What you are doing here is refactoring code, and unfortunately refactoring takes a long time and can be very tedious.

As sdg said, typedefing pointers for shared_ptrs is not a good idea, and just increases the amount of code you have to write.

First, I would identify the pointers that actually need to be changed to shared_ptrs. Obviously you don't want to be changing all pointers to shared_ptrs. Most would probably be better off as std::auto_ptrs or boost::scoped_ptrs and some would be better as boost::weak_ptr, and finally some might just be fine as plain C-style pointers.

Just go through each pointer that needs changing one-by-one, find all references to it, and make the necessary adjustments (e.g. removing calls to delete).

于 2010-02-24T16:36:05.883 回答
0

在将 shared_ptr 引入现有的大型代码库时,我会非常严格。如果您真的想使用智能指针来修复错误,我建议使用范围指针,除此之外,我会重构代码并设计明确的所有权。

于 2010-07-25T08:19:49.410 回答