How to avoid temporary object creation (and deletion) when constructing with initializer list?

Viewed 165

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.

1 Answers
Related