裸机无全球运营商新品 [英] Bare metal without global operator new
问题描述
新
和 delete
时,才允许动态分配。使用运算符 new
为其他类应该导致编译失败。 在描述的情况下,最简单的导致编译失败的方法是删除全局新运算符:
void * operator new(std :: size_t)= delete;
一方面,这会导致标准库的副作用。例如,包含< array>
将< new_allocator>
通过< stdexcept> ;
。 < new_allocator>
使用 :: new
运算符,即使您不想使用异常和内存分配。根据Scoot Meyers < array>
应该是裸机友好的。
另一方面,编译器内置操作符的原因错误
src / main.cpp:91:31:错误:删除'void * operator new(std :: size_t)'的定义
void * operator new(std :: size_t)= delete; ^
< built-in> ;:注意:以前声明的'void * operator new(std :: size_t)'
是否有解决方案禁止 :: new
并使用< array>
?
是否有任何解决方案可以全部禁止全新 c
如果你使用GCC和GNU LD,那么我想你可以添加 - wrap = malloc
到您的链接器标志。由于全局 :: new
在内部使用 malloc()
,所有调用 malloc()
在您的应用程序将被替换为 __ wrap_malloc()
。如果此函数未定义,则链接将失败。
另一个可能更简单的选项是添加 ASSERT(DEFINED(malloc)== 0,动态分配使用!);
到您的链接描述文件。这将断言 malloc()
未定义。
这两个选项都不保护您不重新定义全局 :: new
使用其他形式的全局分配。您可以在链接描述文件中对全局符号 :: new
执行相同的操作,但其名称为mangled(在这里 _Znwj
),所以这会有点奇怪...
Consider safety software, where dynamic allocation in general is disallowed and exceptions are disallowed. Dynamic allocation is allowed only when class explicity defines operator new
and delete
. Using operator new
for others class should cause compilation failure.
The simplest way to cause compilation failure in described situation is to remove global new operator:
void* operator new(std::size_t) = delete;
On the one hand this cause side effects with standard library. For example including <array>
propagates inclusion to <new_allocator>
by <stdexcept>
. <new_allocator>
uses ::new
operator and this cause build fail even when You don't want to use exception and memory allocation. According to Scoot Meyers <array>
should be bare metal friendly.
On the other hand this cause error with compiler built-in operator
src/main.cpp:91:31: error: deleted definition of 'void* operator new(std::size_t)'
void* operator new(std::size_t) = delete; ^
<built-in>: note: previous declaration of 'void* operator new(std::size_t)'
Is there any solution to ban ::new
and use <array>
?
Is there any solution to ban ::new
globally at all?
If you use GCC and GNU LD, then I think you can just add --wrap=malloc
to your linker flags. As global ::new
uses malloc()
internally, all calls to malloc()
in your application will be replaced with __wrap_malloc()
. If this function is undefined, then the linking will fail.
Another, possibly simpler option, is to add ASSERT(DEFINED(malloc) == 0, "Dynamic allocation used!");
to your linker script. This will assert that malloc()
is not defined.
Neither of these options protect you from redefining global ::new
to use some other form of global allocation. You could do the same for global symbol ::new
in the linker script, but its name is mangled (in here _Znwj
), so this will be a little strange...
这篇关于裸机无全球运营商新品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!