Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::make_shared<string>() vs boost::make_shared<string>(string(""))

Tags:

c++

boost

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.

like image 466
q0987 Avatar asked Dec 09 '25 23:12

q0987


2 Answers

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.

like image 193
Mike Seymour Avatar answered Dec 11 '25 12:12

Mike Seymour


make_shared will pass all of its arguments to the constructor of the object it creates. So what will happen is the following:

  1. No arguments, so make_shared will just call something like new string();
  2. You create a temporary 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?
like image 28
Arne Mertz Avatar answered Dec 11 '25 14:12

Arne Mertz



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!