C++中如何正确使用'using'关键字

How to use 'using' keyword properly in C++

我需要了解可以在 C++ 中使用 'using' 关键字的范围。

假设我们在同一代码库中有两个 CPP 文件,它们使用了具有相同类型名称的 'using' 关键字。

A.cpp

#include <iostream>
namespace space_A
{
    typedef struct myStruct
    {
        int a;
        myStruct(): a(1) {}
    } MyStruct;
}

using my_type = space_A::MyStruct;

void func_A()
{
    my_type *t_a = new my_type();
    std::cout<<t_a->a;
}

B.cpp

#include <iostream>
namespace space_B
{
    typedef struct myStruct
    {
        char *b;
        myStruct(): b((char*)"xyz") {}
    } MyStruct;
}

using my_type = space_B::MyStruct;

void func_B()
{
    my_type *t_b = new my_type();
    std::cout<<t_b->b;
}

这两个文件上的“using my_type = ....”行(实际上是使用点-(func_a, func_b))会不会有冲突? 简单地说,'my_type' 是各自文件范围的本地吗?

在提供 正式 变量名范围 定义时,各种 C++ 标准非常冗长(但仍然含糊)以及相关的标识符(比如using关键字引入的alias-declaration)。例如,this Draft (C++17) Standard 表示以下内容:

6.3.1 Declarative regions and scopes
1 Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity. In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope. To determine the scope of a declaration, it is sometimes convenient to refer to the potential scope of a declaration. The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (containing) declarative region.

这(至少对我而言)不是特别有用,除了这句话:确定声明的范围,有时很方便 引用声明的潜在范围。 由此可以推断,如果您不能引用“my_type中给出的定义=47=]" from within "B.cpp," 那么您可以在该文件中提供另一个(可能不同的)这样的定义。

该标准的另一个可能有用的摘录出现在几页之后,在 6.3.6 命名空间范围 部分下:

the potential scope of l is from its point of declaration to the end of the translation unit

此声明也适用于其他声明:每个 my_type 别名的范围是从每个声明的点到翻译单元的末尾(该声明出现的源文件) .

但是,正如在对您的问题的评论中所指出的,尽管这种 'duplication' 别名在 C++ 语言的规则之内,但实践 可能 导致稍后(在 link 阶段)出现问题,尤其是在使用 link-time 代码生成、cross-module run-time linkage(DLL)和调试器等技术时.