0

While going through the Alexander Stepanov original STL(Standard Template Library) source code, I encountered the following from the memory allocator function file: defalloc.h

template <class T1, class T2>
inline void construct(T1* p, const T2& value) {
    new (p) T1(value);
}

I am not able to understand it completely and have the following question/doubts:

  1. It appears to me that it has something to do with copy constructor of type T1?
  2. Why the above function is template on two type T1 & T2?. It should have been T1* for first and *T1 for second(value).
  3. why new has been used in the above logic?. I looked the uses of it and found the following in file vector.h
void push_back(const T& x) {
  if (finish != end_of_storage) {
      construct(finish, x);
        ....
        ....
    }

So based on above, finish has already acquired the memory and been passed into it. The other parameter is x which is value of same type T. These are the few concepts which I am able to think/understand.

It appears to me very general yet important function which has been used throughout STL logic. Could somebody can explain it the above concept?

Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48

1 Answers1

2

It's a placement new, which is a specific kind of new where you specify directly the (already allocated) memory to be used for the value to new.

Why the above function is template on two type T1 & T2?

In this case, it is a placement new that accepts a value to initialize something of a different type through a cast, as you do when you use a constructor for a class. (Note the cast to T1 on the new statement).

You could, for example construct a std::string from a const char* and with placement new in a single, readable, concise function. Here, T1 = std::string and T2 = const char*.

Live example on Coliru

JBL
  • 12,588
  • 4
  • 53
  • 84