简体   繁体   中英

how does namespace and private variables work in assembly?

how does it work? are the variables stored in special registers or memory? im looking at the register/memory windows in visual but i cant understand it :(

#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

int main () {
  using first::x;
  using second::y;
  cout << x << endl;
  cout << y << endl;
  cout << first::y << endl;
  cout << second::x << endl;
  return 0;
}


class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  private:
    int param;
  } rect;

From the machine's perspective, there's nothing different about private or namespace . Those are just identifiers for the compiler. That is, the compiler enforces access rules, which is why you get compiler errors for doing something you shouldn't. The binary code the compiler ultimately produces, however, doesn't make any distinction about what the data is.

The compiler takes

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

and effectively produces assembly code which works something like this:

_first@@x:     dd      5
_first@@y:     dd      10
_second@@x:    dq      3.1416
_second@@y:    dq      2.7183

In case you are not familiar with assembly language, these four statements each reserve memory, two for 32-bit integers, and two for a floating point values, and assign labels to them. A label is a memory address.

Note that the namespace qualifies each variable name. The @ in itself it has no meaning, but escapes the namespace and variable name to isolate unusually named C++ language variables. Assembly language identifiers typically allow a greater range of characters in them than high level languages, convenient in usages such as this.

命名空间用作编译器的方向,因为实际的var名称和方法/类名称在编译后具有不同的名称,因此不使用命名空间名称。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM