简体   繁体   English

自动提供getter和setter函数的基本类C ++

[英]A base class to automatically provide getter and setter functions C++

My use case is like. 我的用例就像。

  1. I have some plain fields, which need a basic thread safe getter and setter. 我有一些简单的字段,需要基本的线程安全的getter和setter。

  2. For some fields a custom getter and setter is required. 对于某些字段,需要自定义获取器和设置器。

What will be the best approach for this problem? 解决此问题的最佳方法是什么?

The standard library provides atomic for simple thread-safe getting and setting of values. 标准库为简单的线程安全获取和设置值提供了atomic http://en.cppreference.com/w/cpp/atomic/atomic http://en.cppreference.com/w/cpp/atomic/atomic

Be aware that proper thread safety almost always involves a lot more than wrapping a few members in std::atomic and calling it a day. 请注意,适当的线程安全几乎总是涉及很多事情,而不是将几个成员包装在std::atomic并每天调用它。

To directly answer the question, I don't believe there is a single good answer to this. 要直接回答这个问题,我认为对此没有一个好的答案。

Unlike C#, C++ doesn't appear to have automatic get , set generation built into the language, and although there might be a complicated way of doing this "organically" (templates, perhaps?); 与C#不同,C ++似乎没有在语言中内置自动getset生成的功能,尽管“有机地”执行此操作可能有复杂的方法(可能是模板)? any solution you might come across might end up being some sort of tool built into an IDE or utility program, such as Eclipse or Code::Blocks. 您可能遇到的任何解决方案最终都可能是某种内置于IDE或实用程序中的工具,例如Eclipse或Code :: Blocks。

Additionally, C++ in its C++03 form is not usually inherently thread-safe; 另外,C ++ 03形式的C ++通常不是天生的线程安全的。 support for multi-threading, thread management, async, and memory safety were added on in later versions (C++11 and on), but due to the nature of C++, I don't believe C++ will ever be inherently thread-safe (at least for now). 在以后的版本(C ++ 11及更高版本)中增加了对多线程,线程管理,异步和内存安全的支持,但是由于C ++的本质,我认为C ++不会固有地具有线程安全性(至少现在(是)。

While std::atomic<type whatever> can be a viable option, you might also want to keep in mind that it is indeed an "add-on" to the language and incurs a time cost, like most other constructs with multi-threading (even atomic operations at the processor level are somewhat slower). 尽管std::atomic<type whatever>可能是一个可行的选择,但您可能还需要记住,它确实是该语言的“附加组件”,并且会像其他大多数带有多线程的构造一样,花费时间。 (即使在处理器级别执行原子操作也较慢)。 You could go the route of mutexes, but again, we're going into multi-threading territory, which may be beyond the scope of your question. 您可以走互斥锁的路线,但同样,我们正在进入多线程领域,这可能不在您的问题范围之内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM