gpt4 book ai didi

c++ - 分配给不同类型时,返回值优化是否有效?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:13:08 26 4
gpt4 key购买 nike

考虑以下两个类:

class Base  
{
Base(const Base& other) {...} // relatively expensive operations here...
Base(int i) {...} // ...here,
virtual ~Base() {...} // ...and here
...
};

class Derived : public Base
{
...
Derived(const Base& other) :Base(other) {...} // some typechecking in here
virtual ~Derived() {}
...
};

这意味着 Base 可以通过 Derived 的第二个构造函数进行“向上转换”。现在考虑以下代码:

Base getBase()  
{
int id = ...
return Base(id);
}
...
int main()
{
Base b = getBase(); // CASE 1
Derived d1(b); // "upcast"

Derived d2 = getBase(); // CASE 2
...
}

我正在使用打开了优化的 VS2008 (/Ox/Ob2/Oi/Ot)。我在控制台输出上检查了对构造函数和析构函数的调用:

案例 1 中,返回值优化有效。有两个调用:

  1. 基础(整数)
  2. ~基础()

但是,当 main 中需要一个 Derived 对象时,这里没有什么可赢的。 “upcast”需要另一个构造函数/析构函数对。

情况 2 中,返回值优化不起作用。这里创建和销毁了两个对象:

  1. Base(int) //创建临时的
  2. ~Base() //销毁临时的
  3. Base(const Base&) //通过 Derived(const Base&)
  4. ~Base() //通过~Derived()

现在在我看来,我有三个相互矛盾的要求:

  1. 我想避免创建临时对象的开销(因为对象创建和销毁在 Base 类中相当昂贵)
  2. main 中,我需要一个 Derived 对象而不是 Base 对象来使用。

显然,天下没有免费的午餐。但我可能错过了什么。所以我的问题是:有没有办法结合这些要求?或者有没有人有过类似的经历?

旁注:我知道这样一个事实,即“upcast”Derived(const Base& other) 可能会在运行时失败(这已得到解决)。由于代码在句法级别上没有问题,我猜这不是编译器避免 RVO 的原因。

最佳答案

这很糟糕。

Derived(const Base& other)   :Base(other) {...}

other 的静态类型可以属于派生类型。在这种情况下,它将被切片。在该基类之上无论如何都会被复制。

RVO 是关于绕过复制构造函数并就地初始化返回的对象。如果您需要派生类型的对象,则必须先构造它。 RVO 无法为您构建它。

您可能需要考虑不同的方法,而不是 Derived(const Base& other)。这个怎么样:

class Base  
{
...
// extract expensive parts of another instance
virtual void initialise(Base& b);
...
};

class Derived : public Base
{
...
Derived(); // cheap constructor
void initialise(Base& b) { /* implementation goes here */ }
...
};

initialise(Base& b) 方法将从参数中提取昂贵 部分。它可能具有破坏性。 Base 将提供公共(public)(或可能 protected )接口(interface)来进行实际提取。

关于c++ - 分配给不同类型时,返回值优化是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5771171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com