【问题标题】:Call of a function with String parameter direct vs variable使用字符串参数直接与变量调用函数
【发布时间】:2017-01-27 17:13:36
【问题描述】:

我遇到了一个问题,我不太了解使用 ESP8266 core for Arduino 在 ESP8266 上开发软件。基本上,如果我传递在调用函数时创建的String,我的程序就会崩溃。我有一个以String 为参数的函数:

void SimpleFunc(String str)
{
    ...
}

我尝试了两种使用很长的String 调用此函数的方法。 第一种方法是创建一个新的String 变量并传递它:

String veryLongString = "veeeerryyyy loooong ........."; //Much longer  in reality!!!
SimpleFunc(veryLongString);

第二种方式是直接传递String

SimpleFunc("veeeerryyyy loooong .........");

运行第二个草图会导致崩溃。这是堆栈的一部分:

umm_assimilate_up at ...\esp8266\2.3.0\cores\esp8266\umm_malloc/umm_malloc.c 第 1163 行

String::~String() at ...\esp8266\2.3.0\cores\esp8266/WString.cpp 第 720 行

_umm_free 在 ...\esp8266\2.3.0\cores\esp8266\umm_malloc/umm_malloc.c 第 1287 行

在 ...\esp8266\2.3.0\cores\esp8266\umm_malloc/umm_malloc.c 第 1733 行免费

String::~String() at ...\esp8266\2.3.0\cores\esp8266/WString.cpp 第 720 行

以这种方式调用函数有什么区别?为什么第一种方法效果很好,第二种方法效果不好?

【问题讨论】:

标签: c++ string arduino esp8266


【解决方案1】:

如果你通过引用调用一个字符串

  void foo(std::string const &str)

没有复制底层字符。如果按值调用

  void food(std::string str)

str 被复制,如果它很长,这是一个昂贵的操作,可能会使机器内存不足。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 2020-10-30
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多