Question 1> Is it true that the usage of Line 1 is better than Line 2?
boost::shared_ptr<string> shpStr = boost::make_shared<string>(); // Line 1
boost::shared_ptr<string> shpStr = boost::make_shared<string>(string("")); // Line 2
Question 2> In general, is it true that we should always use Line 1 instead of Line 2?
boost::shared_ptr<Object> shpStr = boost::make_shared<Object>(); // Line 1
boost::shared_ptr<Object> shpStr = boost::make_shared<Object>(Object()); // Line 2
where Object is a class with default constructor.
Is it true that the usage of Line 1 is better than Line 2?
Yes. The first says what it means: make a shared, default-constructed string. The second adds some unnecessary noise (make a string from an empty string literal, then make another by copying it), and possibly unnecessary runtime overhead, to achieve the same effect.
In general, is it true that we should always use Line 1 instead of Line 2?
Yes. There's no point creating a temporary just to copy and destroy it, rather than just creating the object you actually want.
make_shared will pass all of its arguments to the constructor of the object it creates. So what will happen is the following:
make_shared will just call something like new string();string with argument "", i.e. an empty string. Let's call it tmp. Now make_shared will pass that to the newly created string, i.e. call something like new string(tmp), i.e. in total new string(string("")). So you call the char const* constructor of string, followed by the copy constructor, just to create an empty string. Overkill, isn't it?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