or is there a better way to do this?
Sure, there is a better way, as long we talk about primitive types, or small classes / structs: Just don't.
You can always do that on the stack, I can't see any reason why you ever would need to do that with dynamic memory allocation (unless some esoteric reasons, which would just indicate some serious design flaws).
As for the OP's comment regarding classes / structs:
- If a class grows that big memberwise, that it could be problematic to allocate it on the stack, it's probably better to change the internal class design to do the dynamic allocations internally (e.g. change a large
std::array<T,HUGEVAL>
member variable to a std::vector<T>
).
- Alternatively if you really decide not to, or can't change the class prefer to use a
std::vector
. Using new
and delete
manually is too error prone and should be avoided by all means. There's practically no overhead using a std::vector
, and if your HW is so limited it can't bear that small overhead, dynamic memory allocation won't be available in most cases anyways.
- As the OP pointed out in comments they want to know about the case for class or struct variables: The c++ standard provides
std::unique_ptr
and std::shared_ptr
that can be used to hold and manage a single dynamically allocated type instance, without paying for the std::vector
overhead.
As for the OPs edit (emphasis mine):
What I specifically want to do is to create a class instance in a function and return it without copying it.
There<'s no need to worry about copies made on return
from a function. Modern c++ compilers support RVO (return value optimization), which effectively moves the returned value (see also: Is RVO (Return Value Optimization) applicable for all objects?).