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

This kind of implementation is ugly, and I would not use it in the real case I only want to know using placement new like this are safe or not?Thanks

Thanks to both of you, I alter the codes a little bit, is this safe now?

StereoMatching
  • 4,971
  • 6
  • 38
  • 70
  • Take a look at [this question](http://stackoverflow.com/questions/4583125/char-array-as-storage-for-placement-new). Seems like a duplicate, too. – jrok Nov 04 '12 at 10:53

1 Answers1

0

Not necessarily, because of alignment issues your code may fail, storage_ member must be aligned in a way that can handle alignment of both U and V, so it is not always safe

BigBoss
  • 6,904
  • 2
  • 23
  • 38
  • It highly depend on compiler, for example consider you have `U=std::string`(align = 4) and `V=unsigned char`(align = 1) and your class alignment is 2, then possibly `storage_` also aligned on 2 bytes entry that can't handle `std::string` that require 4. Your code possibly work on most normal compilers, but according to standard it may fail – BigBoss Nov 04 '12 at 11:07