这是来自以下国家的后续问题: constructing string from NULL?
以下:
void test(const std::string& s);
int main(){
test(NULL);
}
运行时失败,但是legal 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是有效类型。
Background:使用cppcheck和cpp core check尝试失败后,我试图查找std::string str = 0
或NULL
或nullptr
的所有情况-因为这些情况在运行时将失败。我认为这可能是前进的道路。
将std :: string解析为:: std :: string以外的其他内容-可以吗?
据我所知,在您的匿名名称空间范围之外是不可能的,因为您无法解决歧义(据我所知)。>>
正如您在下面看到的,由于您位于匿名名称空间的范围内,所以可以:
#include <string> namespace { namespace std { struct string : public ::std::string { }; } std::string hello; // Fine } int main() { std::string hello2; // Cannot be something else that ambiguous return 0; }
但是更糟糕的是,问题不在于
std::string
本身,而是关于std
命名空间。
实际上,在您的匿名名称空间范围之外,对std
的每次调用也变得模棱两可。这是编译器指出的错误。有两个std
命名空间,可以从全局范围访问。
所以下面的例子坏了:
#include <string> #include <vector> namespace { namespace std { struct string : public ::std::string { }; } std::string hello; // Fine } int main() { std::vector<int> a; // FAIL: reference to 'std' is ambiguous return 0; }
因此道德是:
(我愿意接受这个答案的任何改进建议)]] >>