クラスのメンバ変数の使い方について質問があります。クラスがあり、クラス内でパブリックとして宣言されABC
たメンバー変数があるとします。クラスが破棄された後でもBuffer
、どのように変数を使用できますbuffer
か?
buffer
変数を静的として宣言できますか? クラスが破棄された後でも変数にアクセスできますか?
クラスのメンバ変数の使い方について質問があります。クラスがあり、クラス内でパブリックとして宣言されABC
たメンバー変数があるとします。クラスが破棄された後でもBuffer
、どのように変数を使用できますbuffer
か?
buffer
変数を静的として宣言できますか? クラスが破棄された後でも変数にアクセスできますか?
おそらく、いくつかの例が役立つでしょう。
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.
}
オブジェクトの破棄後にメンバーにアクセスできるのは、静的として宣言した場合のみです。これは、クラスのオブジェクトの有効期間に依存しないためです。
ただし、これがユースケースに適合するかどうかはわかりません。変数の名前は です。これはbuffer
、ある種のプロデューサー パターンを意味します。クラスの別のメソッドから静的バッファに書き込むのは、かなり悪い設計です。やりたいことをもっと詳しく説明できますか?
プロデューサーを念頭に置いていると仮定すると、クラスのインスタンスを構築するときに参照によって文字列を渡し、この外部文字列にバッファリングすることが 1 つの解決策になる可能性があります。呼び出し元は、インスタンスの破棄後も結果を保持します。
#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;
}