我对类的成员变量的使用有疑问。
假设,我有一个类ABC
,并且我在类中声明为public的成员变量Buffer
,即使在类被销毁之后我怎么能使用变量buffer
?
我可以将变量buffer
声明为静态吗?即使在类被销毁之后,这是否允许我访问变量?
答案 0 :(得分: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.
}
答案 1 :(得分: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;
}