将std :: string解析为:: std :: string以外的其他内容-可以吗?

问题描述 投票:0回答:1

这是来自以下国家的后续问题: 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 = 0NULLnullptr的所有情况-因为这些情况在运行时将失败。我认为这可能是前进的道路。

c++ c++17 static-analysis argument-dependent-lookup
1个回答
0
投票

将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;
}

因此道德是:

  • 不隐藏现有类型,而是创建一个不同的类型。
  • 以相同的方式,不要隐藏名称空间(通过将相同的名称空间定义为匿名名称空间)。

  • (我愿意接受这个答案的任何改进建议)]] >>

© www.soinside.com 2019 - 2024. All rights reserved.