我必須以我的方式做一點 c 反射,通過為我的類的每個屬性創建一個指標(我創建了一個工具來幫助我生成相應的 c 代碼),但令人驚訝的是,在 x86 模式上構建作業正常,但在 x64模式它崩潰了,我不知道為什么!這是我的代碼。
產品.h 檔案
class Product
{
public:
int ID;
std::string Designation;
};
class Property
{
public:
std::string Name;
int Shift;
};
class ProductSchema
{
private:
ProductSchema();
public:
static ProductSchema* Default();
ProductSchema(const ProductSchema& other) = delete;
Property ID;
Property Designation;
Property Prix;
};
產品.cpp 檔案
ProductSchema::ProductSchema()
{
Product* p = new Product();
ID.Name = "ID";
ID.Shift = (int)(int*)&p->ID - (int)p;
Designation.Name = "Designation";
Designation.Shift = (int)(int*)&p->Designation - (int)p;
}
ProductSchema* ProductSchema::Default()
{
static ProductSchema* instance_;
if (instance_ == nullptr)
instance_ = new ProductSchema;
return instance_;
}
main.h 檔案
int main()
{
for (int i = 0; i < 10000; i )
{
Product* p = new Product();
int* pID = (int*)((unsigned long int)p ProductSchema::Default()->ID.Shift);
*pID = i; // <--- error here
}
}
uj5u.com熱心網友回復:
您的ProductSchema班級和您的main()正在泄漏他們的物件new。
您無需在運行時創建物件來計算其成員的偏移量,您可以offsetof()在編譯時使用。
不要使用int或unsigned long對指標執行計算。它們不能保證足夠大。改為使用(u)intptr_t。
您的單例在使用它之前沒有初始化它的instance_指標。它根本不需要使用動態記憶體。
試試這個:
class Product
{
public:
int ID;
std::string Designation;
};
struct Property
{
std::string Name;
int Shift;
};
class ProductSchema
{
private:
ProductSchema();
public:
static ProductSchema& Default();
ProductSchema(const ProductSchema& other) = delete;
Property ID;
Property Designation;
Property Prix;
};
ProductSchema::ProductSchema()
{
ID.Name = "ID";
ID.Shift = offsetof(Product, ID);
Designation.Name = "Designation";
Designation.Shift = offsetof(Product, Designation);
}
ProductSchema& ProductSchema::Default()
{
static ProductSchema instance_;
return instance_;
}
int main()
{
for (int i = 0; i < 10000; i )
{
Product p;
int* pID = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(&p) ProductSchema::Default().ID.Shift);
*pID = i;
}
}
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441469.html
上一篇:如何在SteelBankCommonLisp(SBCL)中使用`class-direct-superclasses`和`class-precedence-list`?
