Search code examples
c++vectornew-operatordynamic-memory-allocation

In C++, what is the best way to dynamically allocate a single class?


SomeClass* a = new SomeClass;

Is straightforward, but I have heard that std::vector is preferable to new. But,

std::vector<SomeClass> a(1);

also feels weird, because when I use a[0], it's not clear that I'm using it as a variable and not an array. Is there nothing wrong with that, or is there a better way to do this?

Edit: What I specifically want to do is to create a class instance in a function and return it without copying it.

Edit: Changed int to SomeClass.


Solution

  • If you want to dynamically allocate an instance of a class then use a smart pointer: std::unique_ptr or std::shared_ptr which are constructible via make_unique and make_shared respectively.

    There are also libraries with other smart pointers you could use.

    Incase of allocating an int... I mean there could be reasons but normally you should just keep something this small on the stack.