If you want to allocate a dynamic object, it would be
Element* element = new Element;
Because new
returns a pointer to the object in the free store. You have to call delete element
when you're done using the object to prevent memory leaks. If you want to avoid having to manually manage the memory, you can use std::unique_ptr
:
std::unique_ptr<Element> element = new Element;
And element
will call delete
on the pointer automatically when it goes out of scope. However, are you sure you don't want to just create an automatic object?
Element element;
This creates the object in automatic storage and you don't have to manually deallocate it or use smart pointers, and it's a lot faster; it's the best way. (But make sure you don't do Element element();
which is the prototype for a function, not a variable declaration.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…