글로벌 범위와 글로벌 네임 스페이스
이 두 가지 구문 인 전역 범위와 전역 네임 스페이스의 사용법을 확인했습니다. 그들 사이의 차이점은 무엇입니까?
C ++에서 모든 이름은 존재하지 않는 범위 밖에 있습니다. 범위는 여러 방법으로 정의 할 수 있습니다. 네임 스페이스 , 함수 , 클래스 및 {} 만으로 정의 할 수 있습니다 .
따라서 전역 또는 기타 네임 스페이스는 범위를 정의합니다. 전역 네임 스페이스는를 사용하는 것을 나타내며이 네임 스페이스에 ::
정의 된 기호는 전역 범위가 있다고합니다. 기본적으로 심볼은 키워드로 시작하는 블록 내부에 정의되어 있지 namespace
않거나 클래스의 구성원이거나 함수의 지역 변수 가 아닌 경우 전역 네임 스페이스에 존재 합니다.
int a; //this a is defined in global namespace
//which means, its scope is global. It exists everywhere.
namespace N
{
int a; //it is defined in a non-global namespace called `N`
//outside N it doesn't exist.
}
void f()
{
int a; //its scope is the function itself.
//outside the function, a doesn't exist.
{
int a; //the curly braces defines this a's scope!
}
}
class A
{
int a; //its scope is the class itself.
//outside A, it doesn't exist.
};
또한 네임 스페이스, 함수 또는 클래스로 정의 된 내부 범위에 의해 이름 이 숨겨 질 수 있습니다. 따라서 a
네임 스페이스 내의 이름 은 전역 네임 스페이스 N
의 이름 a
을 숨 깁니다 . 같은 방식으로 함수와 클래스의 이름은 전역 네임 스페이스의 이름을 숨 깁니다. 이러한 상황에 직면하면를 사용 ::a
하여 전역 네임 스페이스에 정의 된 이름을 참조 할 수 있습니다 .
int a = 10;
namespace N
{
int a = 100;
void f()
{
int a = 1000;
std::cout << a << std::endl; //prints 1000
std::cout << N::a << std::endl; //prints 100
std::cout << ::a << std::endl; //prints 10
}
}
"범위"는 "네임 스페이스"보다 더 일반적인 용어입니다. 모든 네임 스페이스, 클래스 및 코드 블록은 내부에서 선언 된 이름을 사용할 수있는 범위를 정의합니다. 네임 스페이스는 클래스 및 함수 외부에서 선언 된 이름의 컨테이너입니다.
"글로벌 범위"와 "글로벌 네임 스페이스"는 다소 바꿔서 사용할 수 있습니다. 네임 스페이스에 선언 된 이름의 범위는 해당 네임 스페이스 전체를 포함합니다. 네임 스페이스를 구체적으로 언급하는 경우 "네임 스페이스"를 사용하고 내부 이름의 가시성을 참조하는 경우 "범위"를 사용하십시오.
범위는 개체의 수명을 나타내며, 프로그램이 실행되는 동안 존재하는 전역 변수를 가질 수 있습니다. 또는 해당 코드 블록이 실행되는 동안 존재할 블록 범위가있는 변수를 가질 수 있습니다. 이 예를 고려하십시오.
#include <iostream>
int a = 100;
main () {
int a = 200;
std::cout << "local a is: " << a << std::endl;
std::cout << "global a is: " << ::a << std::endl;
return 0;
}
When executed the statement will print local a is: 200
, that is expected obviously, because we're redefining a
in main
which leaves in the scope of it's enclosing block. We also print the global ::a
which again prints the expected value 100, because we have asked for the global namespace ::
.
A namespace semantics are mostly logical, it is a way of isolating symblos from one another, in the hope to avoid name clashes, it does not affect the lifespan of an object.
Scope on the other hand, denotes the lifespan of an object, the global a
sprung into existence before the local a
because it gets constructed much earlier than main gets executed. However, scope also forces a namespace on the symbol, but not in the same way that a namespace
does. There are different kind of scopes, global
, class
, function
, block
, file
etc...
The confusing part is that scope is sometimes overloaded to denote the visibility of a particular symbol, which is something borrowed from C, where the notion of namespaces did not exist and scope was used to denote both, lifespan and visibility. In C++, however the rules changed a bit,but the term scope is still used the same way because the two languages share a great deal of concepts.
When you declare a global variable int i
for example, we say i is in the global namespace
and has the global namespace scope
. That's all.
Excerpt From C++03:
3.3.5 Namespace scope
The outermost declarative region of a translation unit is also a namespace, called
the global namespace. A name declared in the global namespace has global namespace
scope (also called global scope).
@Dmitriy Ryajov
The topic is a little bit old but I want to offer my help about this. I think that you should not make things more complicated than they really are. Scope
of an identifier is the part of a computer program where the identifier, a name that refers to some entity in the program, can be used to find the referred entity. So the term scope only applies to identifiers and we should not mix it with the lifetime of the object. They are somewhat connected but should not be mixed up. The lifetime of the object is denoted by where we allocate the memory for that object. So, for example, if a memory is allocated on the stack, it will be freed as soon as the function finishes. So it depends on where we store the object and that denotes its lifetime. The scope only says: "Here is a name for an object and we can use this name for the object till then and then". So, as I said, the term scope
is only for identifiers of the objects and the lifetime is something else wich is denoted by where we store the object.
Additionally, I want to say something about linkage
which is closely related to this. This can be also sometimes confusing. Let's say we have some identifiers in the translation unit
that refer to some objects. Whether the same identifiers in other
translation unit will refer to the same entities is denoted by the linkage. So, for example, if an identifier has an external linkage, we can refer to the entity that this identifier refers to but from other translation unit by declaring it with keyword extern
. Now, let's say we don't want to use that entity in other translation units. Then, the entity will exist
till the program finishes but when we don't declare it, we won't be able to refer to it. Also note that now i mixed the terms linkage and lifetime. But this is because only global
entities have external linkage. An identifier inside a function can't be refered to from the other parts of the program.
Conclusion: Always try to keep things simple. I was surprised how different people talk about these terms differently. The whole process of separate compilation is confusing, because there are multiple terms which have almost the same meaning and probably everyone will get stuck at this point.
참고URL : https://stackoverflow.com/questions/10269012/global-scope-vs-global-namespace
'Nice programing' 카테고리의 다른 글
Python 사전의 하위 집합 가져 오기 (0) | 2020.12.08 |
---|---|
Android : 현재 테마의 리소스 ID를 얻는 방법은 무엇입니까? (0) | 2020.12.08 |
정렬 된 세트의 모든 구성원 가져 오기 (0) | 2020.12.08 |
datetime 또는 date 개체 목록을 정렬하려면 어떻게합니까? (0) | 2020.12.08 |
dplyr :: select 함수는 MASS :: select와 충돌합니다. (0) | 2020.12.08 |