You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

clang-tidy警告noexcept函数可能抛异常:该情况是否成立?

问题解析:标记noexcept的std::string返回函数触发clang-tidy警告的原因

代码与警告信息

头文件代码

// .h
[[nodiscard]] auto name() const noexcept -> std::string;

实现文件代码

// .cpp
[[nodiscard]] auto NodeData::name() const noexcept -> std::string {
  return mName;
}

clang-tidy警告

warning: an exception may be thrown in function 'name' which should not throw exceptions [bugprone-exception-escape]


回答

这个函数确实可能抛出异常,触发场景如下:

  • 返回mName时会调用std::string的拷贝构造函数,该函数需要为新字符串分配内存存储原内容。如果系统内存不足,内存分配失败,std::string的拷贝构造函数会抛出std::bad_alloc异常。
  • 函数标记了noexcept,相当于承诺不会抛出任何异常,但实际执行中存在抛异常的可能,违反了noexcept的约定,因此clang-tidy触发了bugprone-exception-escape警告。

解决思路

如果要保持noexcept的承诺,可以改为返回const std::string&,避免触发拷贝构造和内存分配:

// .h
[[nodiscard]] auto name() const noexcept -> const std::string&;

// .cpp
[[nodiscard]] auto NodeData::name() const noexcept -> const std::string& {
  return mName;
}

内容的提问来源于stack exchange,提问作者yonutix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:22:33