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

标签 c++ string pointer-arithmetic placement-new

我想编写一个类,它在内存中保存有关字符串的信息,并可以将其返回给我。所以我从一个 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/

相关文章:

c++ - 你能推荐一些关于 Linux 上 Epoll 的指南吗?

c++ - C++中的静态初始化和线程安全

python - 编码字符串

c++ - 是什么使这个以 '+' 开头的字符串添加成为有效语句?

c++ - 如何使用指针访问 char * 中的字符

c++ - 'strcpy' : cannot convert parameter 2 from 'WCHAR *' to 'const char *

c++ - 如何将字符串转换为 LPTSTR

java - 如何拆分没有模式的文本文件

c - 如何使用指针算术循环分配的内存 C

c++ - C++ 中指针运算的 a+i 和 &a[i] 有什么区别?