【问题标题】:How to access a member variable of a class even after class destruction?即使在类销毁后如何访问类的成员变量?
【发布时间】:2013-07-31 19:56:42
【问题描述】:

我有一个关于类成员变量使用的问题。 假设我有一个类ABC,并且我有一个成员变量Buffer 在类中声明为public,即使在类被销毁后,我如何使用变量buffer

我可以将变量buffer 声明为静态吗?即使在类被销毁后,这是否允许我访问变量?

【问题讨论】:

  • 为什么不在类销毁之前将成员变量分配到仍在范围内的其他地方?
  • 你不会破坏一个类,你会破坏一个类的instances。静态类成员是类的一部分,而不是它的实例。这给你一个提示吗?
  • @RobertHarvey 好吧,我希望即使在类被销毁后也可以访问该变量。我不想将变量复制到仍在范围内的另一个变量。我有一个需要这样做的实时应用程序
  • 如果您将其声明为静态,那么它可以在该类的任何单个实例的生命周期之外访问,但它也将由该类的所有实例共享。如果这是不可接受的,那么您将不得不遵循@RobertHarvey 的建议并在销毁之前将该缓冲区保存在某处。

标签: c++


【解决方案1】:

也许一些例子会有所帮助。

class ABC
{
public:
    std::queue<int> buffer;
};
// All of the above is a class

void foo()
{
    {
        ABC c; // c is now an instance of class ABC.  c is an 
        //object created from class ABC
        c.buffer.push_back(0); // you can change public members of c
    }
    // c is now destroyed.  It does not exist.  There is nothing to access
    // ABC still exists.  The class has not been destroyed
}

但是,有一种可能性:

void foo()
{
    std::queue<int> localBuffer;
    {
        ABC c; // c is now an instance of class ABC.  c is an 
        //object created from class ABC
        c.buffer.push_back(0); // you can change public members of c
        localBuffer = c.buffer;
    }
    // c is now destroyed.  It does not exist.  There is nothing to access
    // ABC still exists.  The class has not been destroyed
    // localBuffer still exists, and contains all the information of c.buffer.
}

【讨论】:

    【解决方案2】:

    只有在将对象声明为静态时,才能在对象销毁后访问该成员,因为它独立于类的任何对象的生命周期。

    但是,我不确定这是否适合您的用例。你的变量被命名为buffer,这意味着某种生产者模式。从您的类中的另一个方法写入静态缓冲区将是一个非常糟糕的设计。你能更详细地解释你想做什么吗?

    假设您有一个生产者,一个解决方案可能是在构造您的类实例时通过引用传递一个字符串,然后缓冲到这个外部字符串。那么调用者在销毁实例后仍然会有结果:

    #include <iostream>
    using namespace std;
    
    class Producer
    {
    public:    
        Producer(string &buffer): m_buffer(buffer) { }
        void produce() { m_buffer.assign("XXX"); };
    protected:
        string &m_buffer;
    };
    
    int main()
    {
        string s;
        Producer p(s);
        p.produce();
        cout << s << endl;
    }
    

    【讨论】:

    • 所以,这个变量存储了图像的宽度值。当我将此变量复制到类范围之外的全局变量中,然后调用全局变量时,出现错误。我现在明白你的代码是什么意思了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 2012-02-08
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多