0
#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];           
};

这种实现很丑陋,我不会在实际情况下使用它我只想知道使用像这样的placement new是否安全?谢谢

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

4

1 回答 1

0

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

于 2012-11-04T10:49:58.437 回答