0

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

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

4

2 回答 2

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.
}
于 2013-07-31T20:07:43.360 回答
0

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

但是,我不确定这是否适合您的用例。您的变量名为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;
}
于 2013-07-31T19:58:15.173 回答