繁体   English   中英

C ++根据条件选择堆栈对象的重载构造函数

[英]C++ choose overloaded constructor for a stack object by condition

我想要这样的东西:

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

任何你不能做的理由

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

要么

KUrl url = customLocation.isEmpty() ? KUrl() : KUrl(customLocation);

通常的C ++构造有意在分配和初始化之间创建非常紧密的耦合。 因此,通常您需要使用动态分配才能动态指定要使用的构造函数。 动态分配的效率可能要比您要避免的轻微开销低几个数量级……

但是,使用C ++ 11 可以使用对齐的存储和新放置。

问题是KUrl类很可能会在内部使用动态分配,然后优化完成的所有工作都是在浪费程序员的时间:既是您最初的时间,也是后来任何人维护代码的时间。

在这里,您没有KUrl副本

boost::optional<KUrl> ourl;
if(customLocation.isEmpty()) {
  ourl = boost::in_place();
} else {
  ourl = boost::in_place(customLocation);
}

KUrl &url = *ourl;

除了有趣,我会推荐Jacks解决方案(如果它适合您的类型):)

url放在外面

KURL url;  // <-- Outside the conditions

if (customLocation.isEmpty())
{
  // Nothing to do
}
else
{
    url = KURL(customLocation);
}

有什么原因不起作用?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM