__declspec(code_seg)
Microsoft 专用
code_seg
声明特性可命名会存储该函数或类成员函数对象代码的.obj
文件中的可执行文本段。
语法
__declspec(code_seg("
segname
"))
declarator
备注
__declspec(code_seg(...))
特性可将代码放置到可在内存中独立分页或锁定的单独命名的段中。 你可以使用该特性控制实例化的模板和编译器生成的代码的放置位置。
段是作为一个单元加载到内存的.obj
文件中的已命名数据块。 文本段是包含可执行代码的段。 术语分区通常与“段”互换使用。
定义 declarator
时生成的对象代码将放入 segname
(窄字符串字面值)指定的文本段。 名称segname
不必事先在分区杂注中指定,即可在声明中使用。 默认情况下,未指定code_seg
时,对象代码将放入名为.text
的段中。 code_seg
特性将重写现有的任何#pragma code_seg指令。 应用于成员函数的code_seg
特性重写应用于封闭类的任何code_seg
特性。
如果一个实体具有code_seg
特性,则同一实体的所有声明和定义必须具有相同的code_seg
特性。 如果一个基类具有code_seg
特性,则派生类必须具有相同的特性。
当code_seg
特性应用于命名空间范围的函数或成员函数时,该函数的对象代码将放入指定文本段中。 该特性应用于类时,类和嵌套类的所有成员函数—包括编译器生成的特殊成员函数—会放入指定段中。 局部定义的类—例如在成员函数主体中定义的类—不继承封闭范围的code_seg
特性。
当code_seg
特性应用于类模板或函数模板时,模板的所有隐式专用化将放入指定段中。 显式或部分专用化不继承主模板中的code_seg
特性。 你可以在专用化时指定相同或不同的code_seg
特性。 code_seg
特性不能应用于显式模板实例化。
默认情况下,编译器生成的代码(例如特殊成员函数)将放入.text
段中。 #pragma code_seg
指令不重写该默认设置。 在类、类模板或函数模板上使用code_seg
特性可控制编译器生成的代码的放置位置。
lambda 继承其封闭范围中的code_seg
特性。 若要为 lambda 指定段,请将code_seg
特性应用于参数声明子句之后,任何可变或异常规范、任何尾随返回类型规范和 lambda 主体之前。 有关详细信息,请参阅 Lambda 表达式语法。 该示例在名为 PagedMem 的段中定义 lambda:
auto Sqr = [](int t) __declspec(code_seg("PagedMem")) -> int { return t*t; };
在不同的段中放入特定成员函数(尤其是虚拟成员函数)时要特别小心。 假设在派生类中定义虚拟函数,当基类方法驻留在非分页段时,该函数驻留在分页段中。 其他基类方法或用户代码可能假定调用虚拟方法不会触发页面错误。
示例
以下示例演示使用隐式和显式模板专用化时,code_seg
特性如何控制段的放置位置:
// code_seg.cpp
// Compile: cl /EHsc /W4 code_seg.cpp
// Base template places object code in Segment_1 segment
template<class T>
class __declspec(code_seg("Segment_1")) Example
{
public:
virtual void VirtualMemberFunction(T /*arg*/) {}
};
// bool specialization places code in default .text segment
template<>
class Example<bool>
{
public:
virtual void VirtualMemberFunction(bool /*arg*/) {}
};
// int specialization places code in Segment_2 segment
template<>
class __declspec(code_seg("Segment_2")) Example<int>
{
public:
virtual void VirtualMemberFunction(int /*arg*/) {}
};
// Compiler warns and ignores __declspec(code_seg("Segment_3"))
// in this explicit specialization
__declspec(code_seg("Segment_3")) Example<short>; // C4071
int main()
{
// implicit double specialization uses base template's
// __declspec(code_seg("Segment_1")) to place object code
Example<double> doubleExample{};
doubleExample.VirtualMemberFunction(3.14L);
// bool specialization places object code in default .text segment
Example<bool> boolExample{};
boolExample.VirtualMemberFunction(true);
// int specialization uses __declspec(code_seg("Segment_2"))
// to place object code
Example<int> intExample{};
intExample.VirtualMemberFunction(42);
}
结束 Microsoft 专用
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈