是否可以在编译时执行唯一的字符串到 int 映射?\n假设我有一个这样的模板用于分析:
\n\ntemplate <int profilingID>\nclass Profile{\npublic:\n Profile(){ /* start timer */ }\n ~Profile(){ /* stop timer */ }\n};\nRun Code Online (Sandbox Code Playgroud)\n\n我将其放在函数调用的开头,如下所示:
\n\nvoid myFunction(){\n Profile<0> profile_me;\n\n /* some computations here */\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在我正在尝试做类似以下的事情,这是不可能的,因为字符串文字不能用作模板参数:
\n\nvoid myFunction(){\n Profile<"myFunction"> profile_me; // or PROFILE("myFunction")\n\n /* some computations here */\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我可以声明全局变量来解决这个问题,但我认为避免以前的声明会更优雅。表格的简单映射
\n\n就足够了。但到目前为止,无论使用 constexpr、模板元编程还是宏,我都无法找到完成此类映射的方法。有任何想法吗?
\n我倾向于使用以下符号:
const Datum& d = a.calc();
// continue to use d
Run Code Online (Sandbox Code Playgroud)
当calc的结果在堆栈上时,这可以工作,参见http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/.即使编译器可能在这里优化,但明确避免临时对象感觉很好.
今天我意识到,d在将数据写入成员之后,内容变得无效a.在这种特殊情况下,get函数只是返回对另一个成员的引用,这与写入完全无关.像这样:
const Datum& d = a.get();
// ... some operation ...
a.somedata = Datum2();
// now d is invalid.
Run Code Online (Sandbox Code Playgroud)
再次,somedata有无关d或get()在这里.
现在我问自己:
我的应用程序是单线程的,除了Qt GUI-Thread.
由于使用共享指针,我经常在我想将它们传递给不必(必须)拥有该对象的函数的情况下运行.因为我知道在函数调用期间对象是有效的,我有四个传递指针的选项:
起初我开始经常使用弱指针(因为我已经有了它们),但是一直锁定它们的开销很烦人并且达到了性能.现在我考虑通过引用传递原始指针或共享指针.有最好的做法吗?