抱歉,标题有点含糊;我将通过一些示例来阐明它。假设我有一个Foo类,其中包含一个init方法:
class Foo{
auto init(const BigMemoryHungryType& t) -> void {
//do a ton of stuff
}
};
现在假设我想创建此init方法的重载,这次接受一个BigMemoryHungryType类型的右值,以便我可以简单地执行move语义:
class Foo{
auto init(const BigMemoryHungryType& t) -> void {
//do a ton of stuff
}
auto init(BigMemoryHungryType&& t) -> void {
//exact same as other init, but utilizing move semantics
}
};
我如何在这里将复制粘贴降至最低?我正在考虑的方法涉及在两个init方法中分配所有成员,然后调用受保护/私有init方法来完成实际工作:
class Foo{
auto init(const BigMemoryHungryType& t) -> void {
real_t = t;
init();
}
auto init(BigMemoryHungryType&& t) -> void {
real_t = std::move(t);
init();
}
private:
auto init() -> void {
//do actual work
}
BigMemoryHungryType real_t;
};
看起来一切正常,但是如果init()引发异常,则会违反强异常保证。我在这里错过明显的东西吗?
尝试这个
auto init(BigMemoryHungryType t) -> void {
init(std::move(t));
}
它将复制BigMemoryHungryType
一次到临时文件,并将其移到移动重载中的实例字段
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句