I was playing around templates when I was surprised that the code below doesn't work as expected:
#include <iostream>
#include <string>
#include <cstring>
template <class Object>
class CreatorTWO {
public:
CreatorTWO (void) {}
~CreatorTWO (void) throw () {}
template <typename... Object_Params>
Object* create (const Object_Params&... params_) {
Object _temp_obj = Object(params_...);
size_t _obj_bytes = sizeof (_temp_obj);
void * _mem_block = std::malloc (_obj_bytes);
std::memmove(_mem_block,&_temp_obj,_obj_bytes);
//The line below prints the dereferenced object before it is returned:
std::cout << *(static_cast <Object*> (_mem_block)) << '\n';
return static_cast <Object*> (_mem_block);
}
};
int main (int argc, char* argv[]) {
CreatorTWO <std::string> _c2;
std::string* _strp = _c2.create("Hello");
std::cout << *_strp << '\n';
std::free (_strp);
return 0;
}
The code above is supposed to create an object with varying number of parameters passed to it. However, when I created an instance templated with std::string to it, passing an argument of "Hello" should give me a pointer to string that contains "Hello". However, this is not the case. If you run the code above, the pre and post values are different with the pre being the correct one. Does anyone know what causes this undesired behaviour? Thanks.