Suppose I have two template classes A and B:
// Non-modifiable template class.
template<class T>
class A{
private:
T* ptr;
int size;
public:
A( int const inputSize ):
ptr{ new T[ inputSize ] }, size{ inputSize }
{}
};
// Modifiable template class.
template<class T>
class B{
private:
A<T> a_obj;
int idx;
public:
B( int const inputSize ):
a_obj{ A<T>{ inputSize } }, idx{ 0 } //temporary object creation?
{}
};
B has a member variable with type A which needs to be constructed during the construction of B. Is there a way to avoid temporary construction of object with type A when constructing B (if it happens at all)? Also please suppose we cannot modify A template class.
What I'm trying to get at is a similar functionality we see with emplace_back() compared to push_back() in vectors: objects are constructed at the place and not twice.
You can (and should) pass the A constructor arguments directly without code implying a temporary, i.e. instead of...
a_obj{ A<T>{ inputSize } }, idx{ 0 } //temporary object creation?
...use...
a_obj{ inputSize }, idx{ 0 }
(Whether the former actually creates a temporary is up to the optimiser).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With