Objective C++ C++ 字符串数组追加时崩溃

Objective C++ Crash on C++ String Array Append

下面的Objective C++例程,如果我运行它在XCode7.1上就足够了OSX 10.11,最终在字符串追加上崩溃。调试器告诉我它每次都在数字 23 处停止(试图附加数字 23)。我想这与内存分配有关。我做错了什么?

调试器打开字符串 class 并卡在下面的 return 语句上。在另一个调试器中 window 它说 (lldb),无论那是什么意思。

template <class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(const basic_string& __str)
{
    return append(__str.data(), __str.size());
}

这是我正在 运行 宁的代码,如果我 运行 例程足够多次,它似乎会导致崩溃。 (这仅在猴子测试期间出现,我在我的 Objective C/C++ 应用程序中点击我的设置菜单足够多次,以至于它触发了以下功能足够多次崩溃。)

std::string Minutes[] = {};
std::string s = "";
for (int i = 1; i<= 59; i++) {
    s = std::to_string(i);
    if (s.length() < 2) {
        s = "0" + s;
    }
    s = ":" + s;
    Minutes->append(s);
}

这可能是一个普通的旧 C++ 问题,也许不是 Objective C++ 问题。或者,也许这是一个 Apple 错误?

请注意,我 运行 进行了以下更改的实验,在 3 次尝试 100 次后,它从未崩溃

std::string Minutes[] = {};
std::string s = "";
for (int i = 1; i<= 59; i++) {
    //s = std::to_string(i);
    /*
    if (s.length() < 2) {
        s = "0" + s;
    }
    s = ":" + s;
    */
    //[Minutes->append(s);
    Minutes->append("01");
}

此外,以下代码补丁也 运行s 3 次,最多 100 次,没有问题:

const std::string Days[] = {"Su","M","T","W","Th","F","Sa"};
std::string Hours[] = {};
for (int i = 1; i <= 12; i++) {
    Hours->append(std::to_string(i));
}

如果您打算在分钟内保留空字符串,请执行以下操作

std::string Minutes[] = {""};

然后 Minutes->append(s); 会将 s 附加到 Minutes[] 数组中的第一个空字符串。

更新时间:

首先你必须创建一个字符串的动态数组(std::vector),以防你不知道数组的大小,并使用索引从 std::vector.

// implies that you used #include <string> and #include <vector>
std::vector<std::string> Minutes;
Minutes.push_back(s)