gpt4 book ai didi

c++ - boost 序列化单例和 sanitizer : null reference

转载 作者:太空狗 更新时间:2023-10-29 23:15:41 27 4
gpt4 key购买 nike

在我使用 boost (1.56) 的程序中使用带有地址清理器的 clang (3.5.1) 我得到:boost/serialization/singleton.hpp:132:13: 运行时错误:引用绑定(bind)到空指针

例子是:

#include<boost/serialization/singleton.hpp> 
#include <string>
#include <iostream>
class Foo{
private:
std::string bar = "Hello World";
public:
void print() const{
std::cout << bar << std::endl;
}
};



int main(){
boost::serialization::singleton<Foo> test;
test.get_const_instance().print();
}

然后我做:

编译

clang++ -I/boost/1_56_0/gcc-4.8.2/include/ -fsanitize=address,undefined -std=c++11 test.cpp

输出

./a.out:
boost/1_56_0/gcc-4.8.2/include/boost/serialization/singleton.hpp:132:13: runtime error: reference binding to null pointer of type 'const Foo'
Hello World

看代码,我对引用实例在类单例中的作用感到困惑。它看起来像未定义的行为。你明白了吗?

template<class T>
bool detail::singleton_wrapper< T >::m_is_destroyed = false;

} // detail

template <class T>
class singleton : public singleton_module
{
private:
BOOST_DLLEXPORT static T & instance;
// include this to provoke instantiation at pre-execution time
static void use(T const &) {}
BOOST_DLLEXPORT static T & get_instance() {
static detail::singleton_wrapper< T > t;
// refer to instance, causing it to be instantiated (and
// initialized at startup on working compilers)
BOOST_ASSERT(! detail::singleton_wrapper< T >::m_is_destroyed);
use(instance); // That's the line 132
return static_cast<T &>(t);
}
public:
BOOST_DLLEXPORT static T & get_mutable_instance(){
BOOST_ASSERT(! is_locked());
return get_instance();
}
BOOST_DLLEXPORT static const T & get_const_instance(){
return get_instance();
}
BOOST_DLLEXPORT static bool is_destroyed(){
return detail::singleton_wrapper< T >::m_is_destroyed;
}
};

最佳答案

我无法让(地址?) sanitizer 在我的 Xcode 6 环境中工作。但我确实使用调试器跟踪了整个程序。 singleton.hpp 的第 132 行包含以下行

使用(实例);

其中实例的值具有(未初始化的零值)。这可能被 sanitizer 认为是一个错误,但 use(...) 是一个空函数。包含它只是为了保证单例在 main 之前被调用。如果不包括在内,为发布而编译可能会优化掉 pre-main 调用,并且该类可能无法按预期运行。所以我认为这是 sanitizer 过度热心的行为。或者, sanitizer 可能被认为不够聪明,无法追踪到更深的一层。或者... .

关于c++ - boost 序列化单例和 sanitizer : null reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28063066/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com