繁体   English   中英

为什么我的 C++ 指向的对象在我的工厂模式中丢失了它的值?

[英]Why does the object my C++ point to lose its values in my factory pattern?

我正在尝试使用工厂模式来创建不同类型的“状态”对象。 对象与指针 (State*) 一起返回,但在创建对象后不久,它们指向的值消失(转到 NULL 或重置为布尔值“true”)。

下面的代码是出错的地方,但下面是一个完整的编译和运行代码示例。 此外,我在 usleep() 命令之前和之后发布了调试器值的图片。

我觉得这可能与作用域和垃圾收集器有关,但无论如何我都不是 C++ 专家。 我原以为我的指针会让我引用的对象保持活动状态。

// relevant code

        void execute(){
            // Calling the constructor directly as an example
            State directState = State("temp", false, false, false);
            // Using factory pattern to create a state.  Just creating the "default" state as an example
            State * factoryState = StateFactory::getDefaultState();
            // factoryState -> name is "Reading" in the debugger, but when I try to print it out, it's gone
            // Grab the names for easy reference
            const char * dName = directState.name;
            const char * fName = factoryState -> name;
            usleep(1000000 / 100);
            // factoryState -> name .... it's vanished?
            usleep(1000000 / 100);
            // TODO we would run the factoryState -> execute() function here
        }

// Complete code example

#include <iostream>
#include <zconf.h>

// Main generic "State" class
class State {
    public:
        const char * name;
        bool isReadable;
        bool isExecuting;
        bool isFinished;

        State(const char name[], bool isReadable, bool isExecuting, bool isFinished){
            this -> name = name;
            this -> isReadable = isReadable;
            this -> isExecuting = isExecuting;
            this -> isFinished = isFinished;
        }
};

// An inherited class.  There will be lots of these eventually
class StateReading: public State { ;
    public:
        StateReading():State((const char *)"Reading", true, false, false) {}
};

// Factory method that will create lots of the different states
// note that it will be returning a pointer to a "State" object
class StateFactory {
    public:
        static State* getDefaultState(){
            StateReading defaultState = StateReading();
            State* state = &defaultState;
            return state;
        }
};

// Runs the various "States" in a template pattern
class StateExecutor {
    public:
        State * state;

        StateExecutor(){
            StateReading stateReading = StateReading();
            state = &stateReading;
        }

        void execute(){
            // Calling the constructor directly as an example
            State directState = State("temp", false, false, false);
            // Using factory pattern to create a state.  Just creating the "default" state as an example
            State * factoryState = StateFactory::getDefaultState();
            // factoryState -> name is "Reading" in the debugger, but when I try to print it out, it's gone
            // Grab the names for easy reference
            const char * dName = directState.name;
            const char * fName = factoryState -> name;
            usleep(1000000 / 100);
            // factoryState -> name .... it's disappeard?
            usleep(1000000 / 100);
            // TODO we would run the factoryState -> execute() function here
        }
};


// The actual
void loop(StateExecutor stateExecutor) {
    // Run the "execute" function of whatever the current state is
    // The stateExecutor actually runs the state
    stateExecutor.execute();
    // Slow the loop down a little.  Just for effect
    usleep(1000000 / 100);
}

// Simple program to recreate an event loop
int main() {

    try {
        StateExecutor stateExecutor = StateExecutor();
        int count = 0;
        do {
            loop(stateExecutor);
            count++;
            // Arbitrarily break out of the loop after 100 events.
        } while(count < 100);
    }  catch (std::exception& e){
        std::cout << e.what() << '\n';
    }
}

以下是工厂创建后的值。 一切看起来都不错。

睡前

嘎! 我调用了 usleep() 并且 factoryState 的 name 字段消失了,bools 已恢复为 true(cout 也这样做)。 黑魔法!

睡后

这里:

    static State* getDefaultState(){
        StateReading defaultState = StateReading();
        State* state = &defaultState;
        return state;
    }

您返回一个指向defaultState的指针。 但是,当函数返回时,此状态将被破坏。 稍后使用此指针是未定义的行为。 您可以将defaultState声明为static ,但我宁愿将其设为静态成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM