使用放置新语法,我应该能够做到这样的事情:
char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
现在假设我只做第一行,但不是第二行。是否有一种方法可以在代码中确定缓冲区是否已正确分配,但是尚未在那里实例化MyClass类型的对象?
答案 0 :(得分:4)
该语言没有提供任何内置机制来提供这些信息,至少没有我所知道的。您必须添加自己的簿记代码才能跟踪此类信息。
答案 1 :(得分:2)
出于调试目的,您可以将特殊成员let relativeY = event.nativeEvent.locationY;
添加到signature
并将其值设置为常量
MyClass
然后,按如下方式检查:
class MyClass {
public:
MyClass() : signature(762347562374) {}
bool isValidSignature() const { return signature==762347562374; }
private:
unsigned long long signature;
<other members>
};
您可以将与签名相关的所有内容放在正确的char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
if (my_class->isValidSignature())
<this means that the object has been allocated correctly, with a high probability>
}
内,以便只在调试模式下运行。
答案 2 :(得分:1)
您可以维护一个static
this
指针值表,您可以在构造函数和析构函数中将其变为MyClass
。然后在需要时针对特定值buffer
进行检查。
不要忘记考虑移动语义的影响。为了做对,会很棘手。
答案 3 :(得分:1)
不是没有自己跟踪它。
一种解决方案是在std::allocator周围创建一个包装器。
template<class T>
class MyAllocator
{
public:
T* allocate(std::size_t count = 1)
{
return allocator_.allocate(count);
}
template<class... Args>
void construct(T* ptr, Args&&... args)
{
allocator_.construct(ptr, std::forward<Args>(args)...);
allocated_ = true;
}
bool IsAllocated() const
{
return allocated_;
}
private:
std::allocator<T> allocator_;
bool allocated_;
};
答案 4 :(得分:1)
原始代码:
char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
要确定动态是否已执行展示位置new
,必须将有关它的信息存储在某处。该语言不提供该服务。所以你必须自己做,主要有两种方式:
()
表达式的末尾添加new
即可。否则,无法保证缓冲区内容看起来不像对象。两个子案例:
bool
变量。