【问题标题】:std::string::erase causes memory corruptionstd::string::erase 导致内存损坏
【发布时间】:2018-04-01 15:22:26
【问题描述】:

我在这个错误上坐了 20 多分钟,但我没有发现任何错误。 std::string::erase 导致错误。

#include <iostream>
#include <string>
#include <cctype>

template <typename ForwardIt>
std::string trimLeft(std::string string_, ForwardIt begin_, ForwardIt end_)
{
    if (!string_.empty())
    {
        auto it = begin_;
        while (it != end_ && std::isspace(static_cast<unsigned char>(*it)))
            ++it;

        string_.erase(begin_, it);
    }
    return string_;
}

std::string trimLeft(std::string string_)
{
    return trimLeft(string_, string_.begin(), string_.end());
}

int main() {
    std::string str{"   left"};
    // Note: this code would work:
    // str.erase(str.begin(), str.begin() + 3);
    std::cout << "|" << trimLeft(str) << "|" << std::endl;
    std::cout << "|" << trimLeft(std::string{"z left"}) << "|" << std::endl;
    std::cout << "|" << trimLeft(std::string{"\tleft"}) << "|" << std::endl;
}

【问题讨论】:

    标签: c++ string algorithm trim erase


    【解决方案1】:

    仔细查看您的签名:

    template <typename ForwardIt>
    std::string trimLeft(std::string string_, ForwardIt begin_, ForwardIt end_)
    //                   ~~~~~~~~~~~~
    

    string_ 是一个值,是您传入的字符串的一个新副本。begin_end_ 是迭代器到...一个完全不同的字符串。所以当你尝试erase

    string_.erase(begin_, it);
    

    您违反了begin_ 实际上是string_ 的迭代器的先决条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多