【发布时间】:2011-09-10 02:44:45
【问题描述】:
我一直误以为成员函数中定义的静态变量仅限于特定的类实例。
为了说明我的误解:
#include <iostream>
#include <string>
struct Simple {
template<typename T>
T & Test(const T & Value) {
static T Storage = Value;
return Storage;
}
};
int main() {
Simple A;
Simple B;
std::string Foo = A.Test(std::string("Foo"));
std::string Bar = B.Test(std::string("Bar"));
std::cout << Foo << ' ' << Bar << std::endl;
}
我预期的行为会导致输出
美食吧
是否有一个简单的替代方案会导致我预期的行为?
编辑
有问题的类的精简版本:
class SignalManager {
private:
template<typename T> struct FunctionPointer { typedef boost::function1<void, const T &> type; };
template<typename T> struct Array { typedef std::vector<typename FunctionPointer<T>::type> type; };
template<typename T>
typename Array<T>::type & GetArray() {
static typename Array<T>::type Array;
return Array;
}
public:
template<typename T, typename M>
void Broadcast(const M & Value) {
typename Array<T>::type::iterator Iterator;
for(Iterator = GetArray<T>().begin(); Iterator != GetArray<T>().end(); ++Iterator) {
(*Iterator)(Value);
}
}
template<typename T, typename F>
void Connect(const F & Function) {
GetArray<T>().push_back(Function);
}
};
【问题讨论】:
-
完全不清楚您要完成什么。如果您删除
static或在静态变量声明后立即执行分配(如 Mahesh 所建议),它们都会为您提供预期的输出。 -
@Victor 在代码示例中,我滥用静态在编译时生成匿名成员变量。对
GetArray的后续调用将返回对匿名成员变量的引用。