我在Boost上遇到了一些麻烦。优化编译时的进程间分配器。我设法将其压缩为40行测试用例,其中大部分是样板文件。请看下面代码中的create()
和main()
函数。
#include <iostream>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace interp = boost::interprocess;
struct interp_memory_chunk
{
interp::managed_shared_memory chunk;
interp_memory_chunk ()
{
interp::shared_memory_object::remove ("GCC_interprocess_test");
chunk = interp::managed_shared_memory (interp::create_only, "GCC_interprocess_test", 0x10000);
}
~interp_memory_chunk ()
{
interp::shared_memory_object::remove ("GCC_interprocess_test");
}
};
typedef interp::allocator <int, interp::managed_shared_memory::segment_manager> allocator_type;
inline void
create (allocator_type& allocator, allocator_type::value_type& at, int value)
{
allocator.construct (allocator.address (at), value);
}
int
main ()
{
interp_memory_chunk memory;
allocator_type allocator (memory.chunk.get_segment_manager ());
allocator_type::pointer data = allocator.allocate (1);
create (allocator, *data, 0xdeadbeef);
std::cout << std::hex << *data << "n";
}
编译这个时,如果没有优化:
g++ interprocess.cpp -lboost_thread -o interprocess
运行,输出为deadbeef
,如预期。
g++ -O1 interprocess.cpp -lboost_thread -o interprocess
运行给出0
, 而不是所期望的。
所以,我不确定问题在哪里。这是一个错误在我的程序,即我调用一些UB?这是Boost.Interprocess中的一个bug吗?或者在GCC中?
为了记录,我在GCC 4.6和4.5中观察到这种行为,但在GCC 4.4或Clang中没有。这里的Boost版本是1.46.1。
EDIT:注意,将create()
作为一个单独的函数是必要的,这可能表明当GCC内联它时出现问题。
正如其他人建议的那样,一个解决方案是尝试找到触发问题所需的最小优化标志集,使用- 01 -fno....
其他选项:
-
使用Valgrind,看看结果如何
-
尝试使用"-fdump-tree-all"编译,这会生成一堆中间编译文件。然后,您可以查看编译后的代码是否有任何差异。这些中间文件仍然是用c++编写的,所以你不需要知道汇编语言。