【问题标题】:Is this implement safe(awkward variant)?这个工具安全吗(尴尬的变种)?
【发布时间】:2012-11-04 10:46:51
【问题描述】:
#include <iostream>
#include <new>
#include <type_traits>

template<typename T, typename U>
struct promote
{
  typedef typename std::conditional<(sizeof(T) > sizeof(U)), T, U>::type type;
};    

template<class U, class V>
class risk_implementation
{
  public:

  template<class T>
  risk_implementation(T const &t)      
  {
    new(storage_) T(t);
  }      

 //easier to do some test with public
 typedef typename promote<U, V>::type Bigger;
 typedef typename std::aligned_storage<sizeof(Bigger), alignof(Bigger)>::type storage_type;
 storage_type storage_[1];           
};

这种实现方式很丑,实际情况下不会用 我只想知道使用像这样的新展示位置是否安全?谢谢

多亏了你们,我稍微修改了一下密码,现在这样安全吗?

【问题讨论】:

标签: c++


【解决方案1】:

不一定,由于对齐问题,您的代码可能会失败,storage_ 成员必须以可以处理 UV 对齐的方式对齐,所以它并不总是安全的

【讨论】:

  • 它高度依赖于编译器,例如考虑你有U=std::string(align = 4) 和V=unsigned char(align = 1) 并且你的类对齐是2,那么可能storage_ 也对齐在无法处理需要 4 的 std::string 的 2 字节条目上。您的代码可能适用于大多数普通编译器,但根据标准它可能会失败
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 2023-03-15
  • 2011-06-19
  • 2012-09-01
  • 2010-10-23
相关资源
最近更新 更多