静态变量重影全局 [英] Static variable shadowing global
问题描述
我正在尝试使用 placement new
创建一个对象(我知道要使用智能指针,这只是为了学习).我的代码如下:
I am trying to create an object using placement new
(I know to use smart pointers, this is just to learn). My code is as follows:
#include <vector>
#include <iostream>
#include <memory>
using namespace std; // please excuse this
// if you change like 19 to arr1 (or any other var name) instead of arr and line 40 to arr1 then it works
struct A
{
int in = 999;
A()
{cout << "A ctor\n";}
~A()
{cout << "A dtor\n";}
};
char arr[sizeof(A)];
class B
{
public:
static char arr[sizeof(A)];
const static A* a_obj;
B()
{
cout << "B ctor\n";
//cout << (a_obj->in) << endl;
}
~B()
{
cout << "B dtor\n";
}
};
const A* B::a_obj = new(arr) A;
int main()
{
B g;
}
我在 B
中创建了一个名为arr的全局数组
和另一个名为 arr
的 array
.看起来当我执行 placement new
时,正在使用的 arr
来自该类,因为我得到的是链接器错误.
I have created a global array
named arr and another array
named arr
in B
. It seems like when I do my placement new
the arr
being used is from the class as I get what I think are linker errors.
为什么会这样?为什么不使用 global arr
?如果我将 placement new
更改为使用重命名的 global数组
,它将起作用.我认为它必须与 lookups
做一些事情,但是我没有具体的答案.
Why is this happening? why isn't the global arr
being used? If i change the placement new
to use my renamed global array
it works. I think it has to do something with lookups
but I don't have a concrete answer.
推荐答案
来自C ++ 2017标准(12.2.3.2静态数据成员)
From the C++ 2017 Standard (12.2.3.2 Static data members)
2在其类中声明非内联静态数据成员定义不是定义,可能是不完整的类型比简历无效.静态数据成员的定义不是类定义中的内联定义应出现在名称空间中包含成员的班级定义的范围.在定义中在名称空间范围内,静态数据成员的名称应为合格的使用::运算符通过其类名来表示.初始化器表达式静态数据成员的定义在其范围内班(6.3.7).
因此在此静态数据成员的定义中
So in this definition of the static data member
const A* B::a_obj = new(arr) A;
首先在类 B
的范围内搜索不合格的名称 arr
.B类确实声明了这样的名字
the unqualified name arr
is at first searched in the scope of the class B
. And the class B indeed declares such a name
static char arr[sizeof(A)];
如果要使用全局名称空间中的名称,请使用限定名称
If you want to use the name from the global namespace then use the qualified name
const A* B::a_obj = new(::arr) A;
这是一个演示程序
#include <iostream>
struct A
{
const static int N = 10;
static int n1;
static int n2;
};
const int N = 20;
int A::n1 = N;
int A::n2 = ::N;
int main()
{
std::cout << "A::n1 = " << A::n1 << std::endl;
std::cout << "A::n2 = " << A::n2 << std::endl;
return 0;
}
其输出为
A::n1 = 10
A::n2 = 20
这篇关于静态变量重影全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!