【发布时间】:2019-01-23 18:40:52
【问题描述】:
我有以下代码:(好吧,实际上它要复杂得多,但我对其进行了简化以使其更易于理解。所以请忽略那些看起来很愚蠢的东西。在我的实际情况下我无法更改它们)
#include <string>
using std::string;
ReportManager g_report_generator;
struct ReportManager
{
// I know, using c_str in this case is stupid.
// but just assume that it has to be this way
string GenerateReport() { string report("test"); return report.c_str(); }
}
string DoIt(bool remove_all)
{
if(g_report_generator.isEmpty())
return string();
string val = g_report_generator.GenerateReport();
if(remove_all)
g_report_generator.clear();
return val;
}
void main()
{
string s = DoIt(true);
}
(N)RVO 会与我的函数一起应用吗? 我做了一些研究,看起来好像是这样,但我不太相信,我想要第二个意见(或更多)。
我正在使用 Visual Studio 2017。
【问题讨论】:
-
它可能会发生也可能不会发生。确定的唯一方法是检查程序集。
-
如果您有
return report;,那么 NRVO 几乎是肯定的。但是,由于您使用.c_str()构造另一个单独的字符串,我认为对于 NRVO 来说这是一个需要考虑的范围。 -
哪个函数?
DoIt或GenerateReport? -
两者。抱歉,我以为我写的是函数,而不是函数。我的错。
-
请发布实际的minimal reproducible example 而不是伪代码。