Originally Posted by
new_ink2001
I was trying to recall if there was a way to call the string member's constructor manually once it had been allocated by malloc...but I don't recall one at the moment.
It's called "placement new", and it should be used only in very special cases.
Code:
#include <string>
#include <iostream>
int main( void )
{
using namespace std;
string* str = static_cast< string* >( malloc( sizeof( string ) ) );
/*
Manually invoke the constructor.
*/
new ( str ) string( "Hello World!" );
cout << *str << endl;
/*
We can't use 'delete' because it may not be compatible with the result of our
'malloc' call, so we have to invoke the destructor and 'free' the memory manually.
*/
str->~string( );
free( str );
}