将字符串存储为char[],位置为new,并将其取回
Storing a string as char[] with placement new and get it back
我想写一个类,它在内存中保存关于字符串的信息,并且可以把它还给我。我从Union开始,它保存字符串的大小。(为什么联合在这里不重要,但它需要其他类型的联合)构造函数得到一个字符串传递,应该把字符串作为c_str放在对象的末尾,我放置新的位置。该类看起来像这样:
class PrimitivTyp
{
public:
explicit PrimitivTyp(const std::string &s);
std::shared_ptr<std::string> getString() const;
private:
union
{
long long m_long; //use long long for string size
double m_double;
} m_data;
ptrdiff_t m_next;
};
函数和函数的含义是这样的,我猜不能正常工作。
PrimitivTyp::PrimitivTyp(const std::string& s)
{
m_data.m_long = s.size();
m_next = reinterpret_cast<ptrdiff_t>(nullptr);
//calc the start ptr
auto start = reinterpret_cast<ptrdiff_t*>(this + sizeof(PrimitivTyp));
memcpy(start, s.c_str(), s.size()); //cpy the string
}
std::shared_ptr<std::string> PrimitivTyp::getString() const
{
auto string = std::make_shared<std::string>();
//get the char array
auto start = reinterpret_cast<ptrdiff_t>(this + sizeof(PrimitivTyp)); //get the start point
auto size = m_data.m_long; //get the size
string->append(start, size);//appand it
return string;//return the shared_ptr as copy
}
用法应该是这样的:
int main(int argc, char* argv[])
{
//checking type
char buffer[100];
PrimitivTyp* typ = new(&buffer[0]) PrimitivTyp("Testing a Type");
LOG_INFO << *typ->getString();
}
这个崩溃了,我找不到调试器的错误。我想是this
的位置计算问题。
this + sizeof(PrimitivTyp)
不是你想的那样,你想要this + 1
或reinterpret_cast<uint8_t*>(this) + sizeof(PrimitivTyp)
。
C和c++中的指针运算考虑了指针的类型。
对于T* t;
, (t + 1)
是&t[1]
(假设operator &
没有过载)或reinterpret_cast<T*>(reinterpret_cast<uint8_t>(t) + sizeof(T))
。