消毒器说
==3044==ERROR: AddressSanitizer: stack-overflow on address 0x7ffcc58b3ff8 (pc 0x56310c340e84 bp 0x7ffcc58b4000 sp 0x7ffcc58b3ff
0 T0)
#0 0x56310c340e84 in boost::operators_impl::operator==(Testable const&, SomeType const&) /home/sehe/custom/boost_1_75_0/boo
问题在于Boost的STRONG_TYPEDEF使得派生类型与基础类型完全有序:
struct SomeType
: boost::totally_ordered1<SomeType, boost::totally_ordered2<SomeType, Testable>>
{
Testable t;
explicit SomeType(const Testable& t_) noexcept((boost::has_nothrow_copy_constructor<Testable>::value)) : t(t_) {}
SomeType() noexcept( (boost::has_nothrow_default_constructor<Testable>::value)) : t() {}
SomeType(const SomeType& t_) noexcept( (boost::has_nothrow_copy_constructor<Testable>::value)) : t(t_.t) {}
SomeType& operator=(const SomeType& rhs) noexcept((boost::has_nothrow_assign<Testable>::value)) {
t = rhs.t;
return *this;
}
SomeType& operator=(const Testable& rhs) noexcept((boost::has_nothrow_assign<Testable>::value)) {
t = rhs;
return *this;
}
operator const Testable&() const { return t; }
operator Testable&() { return t; }
bool operator==(const SomeType& rhs) const { return t == rhs.t; }
bool operator<(const SomeType& rhs) const { return t < rhs.t; }
};
如果您删除了这个隐式转换的源代码:
struct SomeType
: boost::totally_ordered1<SomeType
/*, boost::totally_ordered2<SomeType, Testable>*/>
{
// ...
它只是工作(TM)。我认为您应该将转换运算符explicit
化,并始终进行转换:
在Coliru上实时使用
#include <boost/serialization/strong_typedef.hpp>
#include <iostream>
enum class Testable { UNDEFINED, A, B };
struct SomeType
: boost::totally_ordered1<SomeType
>
{
Testable t;
explicit SomeType(const Testable& t_) noexcept((boost::has_nothrow_copy_constructor<Testable>::value)) : t(t_) {}
SomeType() noexcept( (boost::has_nothrow_default_constructor<Testable>::value)) : t() {}
SomeType(const SomeType& t_) noexcept( (boost::has_nothrow_copy_constructor<Testable>::value)) : t(t_.t) {}
SomeType& operator=(const SomeType& rhs) noexcept((boost::has_nothrow_assign<Testable>::value)) {
t = rhs.t;
return *this;
}
SomeType& operator=(const Testable& rhs) noexcept((boost::has_nothrow_assign<Testable>::value)) {
t = rhs;
return *this;
}
explicit operator const Testable&() const { return t; }
explicit operator Testable&() { return t; }
bool operator==(const SomeType& rhs) const { return t == rhs.t; }
bool operator<(const SomeType& rhs) const { return t < rhs.t; }
};
int main() {
SomeType abc{ Testable::UNDEFINED };
std::cout << "START" << std::endl;
if (abc == SomeType{Testable::UNDEFINED}) {
volatile int j = 0;
}
std::cout << "FINISH" << std::endl;
}
enum class
本身就是强类型,我不清楚为什么需要在其上面再加上其他的“强类型定义”。 - Sam Varshavchikstruct
,其中包含一个enum class
实例作为它们唯一的成员,定义默认的==
和!=
运算符,以及一个构造函数来接收该枚举类(在C++中可能不需要,因为有聚合初始化)。 - Sam Varshavchik