我正在使用带有默认优化设置(/ O2)的VS2012,此问题仅在发布模式下存在。
我有一些代码使用michael_deque
(使用标准GC)和指向(抽象)类型T
的指针。
当我尝试将指针推回到派生自T
的类型时,应用程序在退出push_back()
michael_deque
函数时崩溃。
这个问题似乎完全取决于这个特定类型T
,因为编写了一个虚拟类foo
,在类bar
中从它派生(并在构造函数中打印一些东西以避免它被优化了然后将new bar()
推回到michael_deque不会导致崩溃。
有问题的课程T
是:
class Task
{
public:
Task() : started(false), unfinishedTasks(1), taskID(++taskIDCounter) {};
Task(unsigned int parentID_) : started(false), unfinishedTasks(1), taskID(++taskIDCounter), parentID(parentID_)/*, taken(0)*/ {};
virtual ~Task() = 0 {};
virtual void execute() final
{
this->doActualWork();
unfinishedTasks--;
}
virtual void doActualWork() = 0;
public:
unsigned int taskID; //ID of this task
unsigned int parentID; //ID of the parent of this task
bool started;
std::atomic<unsigned int> unfinishedTasks; //Number of child tasks that are still unfinished
std::vector<unsigned int> dependencies; //list of IDs of all tasks that this task depends on
};
错误可以在最小程序中重现(如果您碰巧有一个可以像我一样执行此操作的环境,只需将std::atomic<unsigned int> taskIDCounter
放在Task类可以看到的地方):
#include <cds/container/michael_deque.h>
#include "task.hpp"
class a : public Task
{
a()
{
std::cout<<"dummy print"<<std::endl;
}
virtual ~a()
{
}
virtual void doActualWork()
{
std::cout<<"whatever"<<std::endl;
}
};
int main()
{
cds::Initialize();
{
cds::gc::HP hpGC;
cds::gc::HP::thread_gc myThreadGC;
cds::container::MichaelDeque<cds::gc::HP,Task*> tasks;
tasks.push_back(new a()); //will crash at the end of push_back
}
cds::Terminate();
}
这可能是什么原因?我是否在类Task中做了一些未定义的事情,这会导致优化问题出现问题?
答案 0 :(得分:5)
这确实是编译器错误。更具体地说,它是与Visual Studio 2012的原子实现相关的错误。
std :: atomic class modify the stack frame pointer (ebp) without backing it up on and popping it form the stack before/after the modification.的一些模板特化libcds库使用这些特化中的一个,产生的错误帧指针有时会导致非法的内存访问(未定义的行为似乎可以防止调试模式中的灾难性故障) )当在函数范围之外运行时。
这个特殊情况下的修复是让libcds使用不同的原子库,然后是Visual Studio提供的标准库。该库决定在cxx11_atomic.h中使用哪个实现:
#if defined(CDS_USE_BOOST_ATOMIC)
# error "Boost.atomic is not supported"
//# include <boost/version.hpp>
//# if BOOST_VERSION >= 105300
//# include <boost/atomic.hpp>
//# define CDS_ATOMIC boost
//# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace boost {
//# define CDS_CXX11_ATOMIC_END_NAMESPACE }
//# else
//# error "Boost version 1.53 or above is needed for boost.atomic"
//# endif
#elif CDS_CXX11_ATOMIC_SUPPORT == 1
// Compiler supports C++11 atomic (conditionally defined in cds/details/defs.h)
# include <cds/compiler/cxx11_atomic_prepatches.h>
# include <atomic>
# define CDS_ATOMIC std
# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace std {
# define CDS_CXX11_ATOMIC_END_NAMESPACE }
# include <cds/compiler/cxx11_atomic_patches.h>
#else
# include <cds/compiler/cxx11_atomic.h>
# define CDS_ATOMIC cds::cxx11_atomics
# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace cds { namespace cxx11_atomics {
# define CDS_CXX11_ATOMIC_END_NAMESPACE }}
#endif
if语句的第二个分支可以更改为
#elif CDS_CXX11_ATOMIC_SUPPORT == 255
这将导致库始终使用自己的原子实现。