gpt4 book ai didi

c++ - 将字符串存储为 char[] 并放置新的并将其取回

转载 作者:行者123 更新时间:2023-11-30 05:38:27 24 4
gpt4 key购买 nike

我想编写一个类,它在内存中保存有关字符串的信息,并可以将其返回给我。所以我从一个 Union 开始,它包含一个字符串的大小。 (为什么 union 在这里无关紧要,但稍后它需要成为其他类型的 union)构造函数获取一个字符串并应将该字符串作为 c_str 放在我放置新位置的 Objekt 的末尾。该类看起来像这样:

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;
};

Ctor 和 get 函数的实现看起来像这样,我猜它不能正常工作。

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 + 1reinterpret_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)) .

关于c++ - 将字符串存储为 char[] 并放置新的并将其取回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32777278/

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