Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 887
Farzad Avatar asked Feb 11 '26 01:02

Farzad


1 Answers

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).

like image 60
Tony Delroy Avatar answered Feb 13 '26 15:02

Tony Delroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!