basin
basin

Reputation: 4190

C++ choose overloaded constructor for a stack object by condition

I want something like this:

if (customLocation.isEmpty())
{
    KUrl url;
}
else
{
    KUrl url(customLocation);
}
/* use url */

Upvotes: 1

Views: 182

Answers (5)

Cheers and hth. - Alf
Cheers and hth. - Alf

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

Johannes Schaub - litb
Johannes Schaub - litb

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

David G
David G

Reputation: 96845

KUrl url;

if (!cusomLocation.isEmpty())
{
    url = KUrl( customLocation );
}

Upvotes: 0

john
john

Reputation: 88007

Any reason why this won't work?

KUrl url;
if (!customLocation.isEmpty())
    url = customLocation;

Upvotes: 0

Jack Aidley
Jack Aidley

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

Related Questions