There is a little code example here:
struct Data {
};
struct Init {
Data *m_data;
Init() : m_data(new Data) { }
~Init() {
delete m_data;
void callInitA() {
Init x;
somefunction(x); // calls the "const Init &" constructor
}
The destruction of x
cannot be optimized away, regardless of the contents of Init
. Doing so would violate the design of the language.
It's not just a matter of whether Init
contains resources or not. Init x
, like all objects, will allocate space on the stack that later needs to be cleaned up, as an implicit (not part of code that you yourself write) part of the destructor. It's impossible to avoid.
If the intention is for x
to be an object that somefunction
can call without having to repeatedly create and delete references to x
, you should be handling it like this:
void callInitA(Init & x) { //Or Init const& x
somefunction(x); // calls the "const Init &" constructor
}
A few other notes:
std::unique_ptr
, as it doesn't seem like you need functionality beyond what std::unique_ptr
offers.