Reputation: 4190
I want something like this:
if (customLocation.isEmpty())
{
KUrl url;
}
else
{
KUrl url(customLocation);
}
/* use url */
Upvotes: 1
Views: 182
Reputation: 145419
The usual C++ constructs intentionally create a very tight coupling between allocation and initialization. Thus, ordinarily you would need to use dynamic allocation to be able to dynamically specify the constructor to use. And dynamic allocation is probably some orders of magnitude more inefficient than the slight overhead that you're trying to avoid…
However, with C++11 you can use aligned storage and placement new.
The catch is that the KUrl
class will most likely use dynamic allocation internally, and then all that the optimization accomplishes is to waste programmer's time: both your time initially, and the time of anyone later maintaining the code.
Upvotes: 1
Reputation: 507245
Here you have no copy of KUrl
being done
boost::optional<KUrl> ourl;
if(customLocation.isEmpty()) {
ourl = boost::in_place();
} else {
ourl = boost::in_place(customLocation);
}
KUrl &url = *ourl;
Fun aside, I would recommend Jacks solutions (if it works with your type) :)
Upvotes: 0
Reputation: 96845
KUrl url;
if (!cusomLocation.isEmpty())
{
url = KUrl( customLocation );
}
Upvotes: 0
Reputation: 88007
Any reason why this won't work?
KUrl url;
if (!customLocation.isEmpty())
url = customLocation;
Upvotes: 0
Reputation: 20107
Any reason you can't do
KUrl url;
if (!customLocation.isEmpty())
{
url = KUrl(customLocation);
}
/* use url */
or
KUrl url = customLocation.isEmpty() ? KUrl() : KUrl(customLocation);
Upvotes: 1