查找表应该是静态的吗
我有一个 Message 类,它使用查找表来解析文本消息。 我收到很多消息并创建和销毁很多对象,所以我想我将这些查找表声明为静态成员,以防止一次又一次使用相同的值初始化相同的表。
这是正确的方法还是有更合适的 C++ 方法?
谢谢。
I have a Message class which parses text messages using lookup tables. I receive a lot of messages and create and destroy a lot of objects so I thought I declare those lookup tables as static members to prevent initializing the same tables with the same values again and again.
Is it the correct approach or there's more appropriate C++ way?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的消息类共享查找信息,则可能值得将静态查找抽象到它们自己的类中,以便它们实际上只初始化一次。
但无论如何,静态类成员绝对是正确的选择。
If your message classes share lookup information that it may be worth abstracting your static lookups into a class of their own so that they really are only initialised once.
But regardless, static class members are definitely the way to go.
它们可以是类变量,即类级别的静态变量。 这样,它们就可用于子类(如果有),并且可能比在各个方法中作为静态局部变量“隐藏”更明显。
They could be class variables, i.e. static at the class level. That way they are available to subclasses, if any, and perhaps a bit more visible than if "hidden" as static local variables in individual methods.
这听起来像是正确的方法,尽管我希望编译器能够优化它。 您是否对您的应用程序进行了基准测试,并将表声明为静态是否会加快速度?
另请注意,如果您有许多大型查找表,性能将会提高,但这些表将始终保存在内存中。
This sounds like the right way to do it, although I'd expect the compiler to optimize this. Have you benchmarked your application and does declaring the tables as static speed it up?
Also note that if you have many large lookup tables, performance will increase, but the tables will be hold in memory all the time.
是的,一切都好。 有时这是一个很好的解决方案:静态函数只会创建一次。 您也可以使用单例对象,但它具有更广泛的可访问性。
如果您有多线程应用程序,并且您的查找表包含指向另一个数据的指针,而该数据可能早于该表被销毁,请小心。
Yes, all ok. Sometimes it is good solution: function static which will created only once. Also you could use singleton object, but it has more wide accessibility.
Be careful if you have multi-threaded application and if your lookup-tables contain pointer to another data which could be destroyed early than this table.
使用单例模式也可以达到此目的。
Using a singleton pattern will also work for this.