Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix address_of for overloaded operator& #139

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions MyTinySTL/memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,43 @@ namespace mystl
{

// 获取对象地址
// 尽可能使用支持 constexpr 的 __builtin_addressof
#ifdef __has_builtin
#define MYTINYSTL_HAS_BUITIN_ADDRESSOF __has_builtin(__builtin_addressof)
#elif __GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >=70000
#define MYTINYSTL_HAS_BUITIN_ADDRESSOF 1
#elif _MSC_VER >= 1910
#define MYTINYSTL_HAS_BUITIN_ADDRESSOF 1
#else
#define MYTINYSTL_HAS_BUITIN_ADDRESSOF 0
#endif

#if MYTINYSTL_HAS_BUITIN_ADDRESSOF
template <class Tp>
constexpr Tp* address_of(Tp& value) noexcept
{
return __builtin_addressof(value);
}
#else
// 对于对象类型和函数类型分别使用不同的策略
template <class Tp, typename std::enable_if<std::is_object<Tp>::value, int>::type = 0>
Tp* address_of(Tp& value) noexcept
{
return const_cast<Tp*>(reinterpret_cast<const volatile Tp*>(
&reinterpret_cast<const volatile unsigned char&>(value)));
}

template <class Tp, typename std::enable_if<!std::is_object<Tp>::value, int>::type = 0>
constexpr Tp* address_of(Tp& value) noexcept
{
return &value;
}
#endif

#undef MYTINYSTL_HAS_BUITIN_ADDRESSOF

template <class Tp>
void address_of(const Tp&&) = delete; // 避免对临时对象取地址

// 获取 / 释放 临时缓冲区

Expand Down