我想在编译时跟踪一些当前采用相同类型参数的函数的基本“类型”信息。这是一个例子;假设我有两个函数 getThingIndex(uint64_t t)
和 getThingAtIndex(uint64_t tidx)
。第一个函数将参数视为 thing
的编码,对索引进行非平凡的计算,然后返回它。然后可以通过调用 getThingAtIndex
获取实际的“事物”。另一方面,getThingAtIndex
假定您正在查询结构并且已经有一个索引。这两种方法中的后者更快,但更重要的是,我想避免将 thing
传递给 getThingAtIndex
或传递 可能导致的麻烦index
到 getThingIndex
。
我正在考虑为 thing
和事物索引创建类型,就像这样:
struct Thing { uint64_t thing; }
struct ThingIndex { uint64_t idx; }
然后将上述函数的签名更改为
getThingIndex(Thing t)
getThingAtIndex(ThingIndex idx)
现在,尽管 Thing
和 ThingIndex
编码相同
底层类型,它们在编译时仍然是不同的,我
通过将索引传递给来减少犯愚蠢错误的机会
getThingIndex
或 getThingAtIndex
的事物。
但是,我担心这种方法的开销。功能 被调用了很多次(10s-100s of millions),我很好奇 编译器将优化这些结构的创建,这些结构本质上是 除了编码编译时类型信息外什么都不做。如果编译器不会 执行这样的优化,有没有办法创建这些类型的“丰富类型” 零开销?
最佳答案
看一下反汇编。
unsigned long long * x = new unsigned long long;
0110784E push 8
01107850 call operator new (01102E51h)
01107855 add esp,4
01107858 mov dword ptr [ebp-0D4h],eax
0110785E mov eax,dword ptr [ebp-0D4h]
01107864 mov dword ptr [x],eax
*x = 5;
01107867 mov eax,dword ptr [x]
0110786A mov dword ptr [eax],5
01107870 mov dword ptr [eax+4],0
还有结构。
struct Thing { unsigned long long a; };
Thing * thing = new Thing;
0133784E push 8
01337850 call operator new (01332E51h)
01337855 add esp,4
01337858 mov dword ptr [ebp-0D4h],eax
0133785E mov eax,dword ptr [ebp-0D4h]
01337864 mov dword ptr [thing],eax
thing->a = 5;
01337867 mov eax,dword ptr [thing]
0133786A mov dword ptr [eax],5
01337870 mov dword ptr [eax+4],0
两条指令没有区别。编译器不关心 this->a
是结构的成员,它访问它就像您刚刚声明 unsigned long long a
一样。
关于c++ - C++ 中 "rich type"结构的开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15689553/