C++ 异常使用 placement new into NULL
C++ unusual use of placement new into NULL
在the following C++98 statement中:
multiThreadService[nextBuffer] = new (NULL) MultiThreadService(binder);
这样说对吗:
- 这是“新展示位置”,
- 对象将被创建(以某种方式为 NULL?)并被丢弃,并且
multiThreadService[nextBuffer]
现在将为 NULL?
我还被告知这可能是 UB - 是这样吗?
首先,它不一定是调用全局non-allocating placement-new operator new
重载void* operator new(std::size_t size, void* ptr)
(通常所说的“placement new".)
因为 new-expression 不符合 ::new
,它可能更喜欢 operator new
的 in-class 重载(如果存在合适的重载)并且 [=] 的类型14=] 不是 void*
,而是 std::nullptr_t
或整数类型(前者在 C++98 中是不可能的)。因此,即使在全局情况下,重载决议也有一些潜在的替代结果。
在项目中搜索 operator new
重载可以在 https://github.com/aneto0/MARTe2/blob/master/Source/Core/BareMetal/L2Objects/CLASSREGISTER.h#L85 找到至少一个可能的候选者,这似乎 return 一个有效的指针,即使放置参数(第二个函数参数) 是一个空指针。
如果选择的重载确实是全局 non-allocating placement-new operator new
,那么它基本上是 C++98 中的空指针,导致空指针。 new
如果 operator new
return 是一个空指针,则要求表达式不进行任何初始化。
然而,这已被 CWG 1748 更改,现在如果全局 non-allocating placement-new operator new
return 是一个空指针值,则行为未定义。这也可能被认为是针对 C++98 的缺陷(我不知道),在这种情况下 -std=c++98
不会阻止当前编译器上的未定义行为。
在the following C++98 statement中:
multiThreadService[nextBuffer] = new (NULL) MultiThreadService(binder);
这样说对吗:
- 这是“新展示位置”,
- 对象将被创建(以某种方式为 NULL?)并被丢弃,并且
multiThreadService[nextBuffer]
现在将为 NULL?
我还被告知这可能是 UB - 是这样吗?
首先,它不一定是调用全局non-allocating placement-new operator new
重载void* operator new(std::size_t size, void* ptr)
(通常所说的“placement new".)
因为 new-expression 不符合 ::new
,它可能更喜欢 operator new
的 in-class 重载(如果存在合适的重载)并且 [=] 的类型14=] 不是 void*
,而是 std::nullptr_t
或整数类型(前者在 C++98 中是不可能的)。因此,即使在全局情况下,重载决议也有一些潜在的替代结果。
在项目中搜索 operator new
重载可以在 https://github.com/aneto0/MARTe2/blob/master/Source/Core/BareMetal/L2Objects/CLASSREGISTER.h#L85 找到至少一个可能的候选者,这似乎 return 一个有效的指针,即使放置参数(第二个函数参数) 是一个空指针。
如果选择的重载确实是全局 non-allocating placement-new operator new
,那么它基本上是 C++98 中的空指针,导致空指针。 new
如果 operator new
return 是一个空指针,则要求表达式不进行任何初始化。
然而,这已被 CWG 1748 更改,现在如果全局 non-allocating placement-new operator new
return 是一个空指针值,则行为未定义。这也可能被认为是针对 C++98 的缺陷(我不知道),在这种情况下 -std=c++98
不会阻止当前编译器上的未定义行为。