c++smart-pointersmember-initialization

What is a disadvantage of initializing a smart pointer data member in a member initializer list?


Let's say there is a class B which has a smart pointer member for a pointer to object of class A. Then, what is a disadvantage of initializing the smart pointer member in a member initializer list? I know that initializing is faster than assignment (would be resetting here), but I have no idea about disadvantages. What is a disadvantage of initializing a smart pointer in a member initializer list?

#include <chrono>
#include <iostream>
#include <memory>

struct A {
};

struct B1 {
    B1(): a(new A) {}
    std::unique_ptr<A> a;
};

struct B2 {
    B2() {
        a.reset(new A);
    }
    std::unique_ptr<A> a;
};

int main() {
    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
    for(auto i=0; i < 100000; ++i) {
        B1 b;
        // B2 b;
    }
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    std::cout << (end - begin).count() << std::endl;
}

B1: 8054043, B2: 8894576


Solution

  • There is no disadvantage and you should initialize it in the member initializer list. However I doubt it will make any performance difference at all. (Your test doesn't work. It is either done without optimizations enabled or measuring random noise.)

    However usually it is recommended to not use new directly, but std::make_unique instead.

    Also, if the value that is going to be initialized doesn't depend on the arguments to the constructor using a default initializer might be a better approach:

    struct B1 {
        std::unique_ptr<A> a = std::make_unique<A>();
    };