-2

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

Han
  • 625
  • 2
  • 7
  • 25
  • 3
    Why do you think there are any disadvantages of initializing here? – Jason Oct 11 '22 at 10:51
  • 3
    For profiling you should only use release builds. And it's likely that all the code constructing `B1`/`B2` objects will get eliminated by the optimizer. So I'm not sure you measured what you thought. – wohlstad Oct 11 '22 at 10:54
  • @JasonLiam I simply thought there could be any disadvantage or side effects that I don't imagine, but I failed to find online. Hence, I posted a question. – Han Oct 11 '22 at 11:48
  • @wohlstad My bad. I forgot to enable optimization, and thought resetting in the body takes more time as it requires `nullptr` initialization. – Han Oct 11 '22 at 11:52

1 Answers1

1

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>();
};
user17732522
  • 53,019
  • 2
  • 56
  • 105
  • Thank you for your advice. Yes, I was supposed to enable optimizations and iterate more to minimize noises. – Han Oct 11 '22 at 11:55