【发布时间】:2019-10-11 09:45:15
【问题描述】:
这是来自: constructing string from NULL?
的后续问题以下内容:
void test(const std::string& s);
int main(){
test(NULL);
}
运行时失败,但合法 c++。
为了尝试捕捉其中一些情况,作为替代方案,我考虑是否可以通过以下方式替换 std::string:
#include <string>
namespace {
namespace std {
struct string : public ::std::string { //so far everything is good
};
}
}
int main ()
{
std::string hello;//failure: ambiguous symbol
return 0;
}
给出以下错误:
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
Compiler returned: 2
我想如果不写一个更(完全)合格的名称就不可能解决它?但是是否可以在全局命名空间中写入 std::string 并让它解析为其他东西,而 ::std::string is 是一个有效类型。
背景:在尝试使用 cppcheck 和 cpp 核心检查失败后,我试图找到所有 std::string str = 0 或 NULL 或 nullptr 的案例 - 因为这些案例将在运行时失败。我认为这可能是一个前进的方向。
我最终修改了 basic_string 模板。 basic_string(int) = delete;
basic_string(::std::nullptr_t) = delete; - 这不会捕获所有案例,但似乎确实至少可以捕获直接案例
【问题讨论】:
-
我首先要问 - 为什么要将
std::string查找解析为其他内容? -
@bartop 查看问题的最后一部分,背景
-
你为什么要“抓住”它?那有什么意思?为什么
std::string str = 0首先出现在您的代码中?您为什么不修复这些代码错误,而不是尝试编写一个尝试隐藏错误的自定义类型?很抱歉一堆问题,但您似乎有一个 XY 问题,最好详细解释您的情况和目标。不要向我们展示您的(尝试)解决方案,向我们展示您的问题。 -
一些额外的想法:如果您担心正则表达式无法在您的代码中找到此问题的所有情况 - 您如何确保能够在每个地方注入此自定义类型它需要在哪里的代码?如果你想用一个自定义类型替换
std::string,它会默默地忽略nullptr分配,为什么不简单地用MyCustomNullPtrSafeString替换代码库中所有出现的std::string,而不是一个名为std::string的自定义类型? -
您的问题也应该是独立的。如果阅读您发布的其他问题或其他外部信息有助于全面了解您的情况,您可能需要链接到该外部信息并在您的问题中进行总结。
标签: c++ c++17 static-analysis argument-dependent-lookup