C++指针参数在'ret'指令之前设置为NULL

Vol*_*lte 4 c++ templates pointers arguments

我有一个奇怪的问题.我以为我知道一定数量的C++,但我必须忽略一些细微差别?

我有一些模板化的类,基本上所有发生的事情都是基于某些条件,一个对象正从一个std :: list移动​​到另一个.

这里关注的方法是doAndGet(T*t).我的目的是让T对来作为NULL(或什么的,我真的不在乎,但它应该是NULLnullptr,如果我结束了移动T元素*t,从myListmyOtherList,我想T *t以指向已移动的项目.

现在也许有一些std::list我不知道的事情,但是当我踩过我的代码时,t得到了正确的分配 - 原来我想在返回的方法之后,但后来发现 - 就在ret指令之前,参数T *t被设置回NULL

任何一位大师都可以对这个问题有所了解吗?对我来说这真是令人头疼的事......

template<typename T, typename C>
class Base : IsDerivedFrom<T, C>
{
public:
    typedef std::list<T*> SpecialList;
    virtual bool doAndGet( T* t ) = 0;

protected:

    SpecialList myList;
};

template<typename T>
class Derived : public Base<T, Other>, public Other
{
public:
    Derived( void );
    virtual ~Derived( void );

    bool doAndGet( T* t );

protected:

    typename Base<T, Other>::SpecialList myOtherList;

};

template<typename T>
bool Derived<T>::doAndGet( T *t )
{
    // Nothing to process
    if (myOtherList.empty()) {return false;}

    t = (*myOtherList.begin());
    myOtherList.pop_front();

    if (true/* some condition needs to be moved */)
    {
        t->status = 1;
        this->myList.push_back(t);
        return true;
    } else
    {
        // Something bad happened...
        delete t;
        t = nullptr;
        return false;
    }
}

// Use... (pretend I defined MyOtherClass somewhere, not important)
Derived<MyOtherClass> derivedInstance;

MyOtherClass *t = nullptr;
if ( derivedInstance.doAndGet(t) )
{
    // ... Here I should expect `t` to be not `NULL` and not `nullptr`
    // This however, is not ever the case in my testing...
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 6

如果要将变量传递给函数并在该函数中进行任何更改以反映回调用者,则需要使用引用.

像C一样,C++是按值传递的,其中函数只获取变量的副本.C++有引用允许通过引用传递.

换句话说,您的函数签名应该是:

bool doAndGet( T* &t );
Run Code Online (Sandbox Code Playgroud)

声明t是对a的引用T*,允许更改反映回调用者中的原始指针.

一个更简单的例子如下:

#include <iostream>
static void change (int a, int &b) { a = b = 0; }
int main() {
    int a = 42, b = 42;
    change (a, b);
    std::cout << a << ' ' << b << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这会输出,42 0因为a传入的值是按值传递的,更改不会反映回调用者.所述b被传递在作为参考,以便改变反射回来.