Here is my program:
#include <iostream>
using namespace std;
class Object {
public:
Object() { cout << "Object constructor!" << endl; }
~Object() { cout << "Object destructor!" << endl; }
Object(const Object& obj) { information = obj.information; cout << "Copy constructor!" << endl; }
void setInformation(const string info) { information = info; }
string getInformation() const { return information; }
private:
string information;
};
class Storage {
public:
Storage() { object = static_cast<Object*>(operator new(sizeof(Object))); }
~Storage() { operator delete(object); }
void setObject(const Object& obj) {
// Todo: assign obj to the allocated space of the pointer object
}
private:
Object* object;
};
int main()
{
Object o;
o.setInformation("Engine");
Storage storage;
storage.setObject(o);
return 0;
}
In Storage I am allocating space to store one object of type Object without creating it. I am using placement new for that which allocates a memory, and freeing it in the destructor. I know that I can use
object = new(object) Object()
to construct an object. But can I put in the memory an object that is already created? In my case call method setObject(). If yes what problems I can encounter with such memory management? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire