gpt4 book ai didi

c++ - 如何判断一个对象是否有堆分配成员?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:33 24 4
gpt4 key购买 nike

有没有办法确定一个对象是否至少有一个成员在堆上?

我正在尝试能够区分像 std::stringstd::vectorstd::list 这样的对象(是的主要是容器)来自所有其他类型(不幸的是,即使只有一个元素的容器也在我的“兴趣范围内”)

我正在尝试执行以下操作:

struct foo
{
private:
int * _ptr;

public:
foo() : _ptr(new int) {};
~foo() { delete _ptr; };
};

struct bar
{
private:
int val;
};

template <typename T>
void func(T val)
{
if constexpr (std::is_class_v<T>)
{
std::cout << std::setw(20) << typeid(T).name() << " is a class type." << std::endl;
if (/* determine if foo has any heap allocations */)
{
// Do something #1.
std::cout << std::setw(20) << typeid(T).name() << " does allocate on heap." << std::endl;
}
else
{
// Do something #2.
std::cout << std::setw(20) << typeid(T).name() << " does NOT allocate on heap." << std::endl;
}
}
else
{
// Do something #3.
std::cout << std::setw(20) << typeid(T).name() << " is NOT a class type." << std::endl;
}
}

int main()
{
func(foo()); // foo does allocate on heap
cout << endl;

func(bar()); // bar does NOT allocate on heap
cout << endl;
};

foobar 只是示例,函数 func() 必须执行与 cout 有点不同的功能 控制台。

最佳答案

This is XY problem... I am trying to write a hash function that will be aware whether the user-defined key type stores any data on an array (just like std::string` would). I am fairly able to create a generic hash function that takes any type, but if that type has an array (a pointer) to some of it's stored data, problems become very tricky (pointers to dynamic arrays change at runtime, the same key at, different times will produce different hash value)

请注意,某些结构/类类型具有内部未初始化的填充,这可能会使您的哈希函数无法正常工作。

否则,std::is_trivially_copyable 将是一个好的开始。

关于c++ - 如何判断一个对象是否有堆分配成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com