English 中文(简体)
当最后一次使用可移动对象时,编译器是否自动使用移动语义?
原标题:Do compilers automatically use move semantics when a movable object is used for the last time?

我最近一直在研究右值引用,得出的结论是,在将要对对象进行完整复制的任何地方都使用按值传递是非常有利的(有关完整的理由,请参阅例如添加右值引用运算符重载时如何减少冗余代码?想要速度?按值传递!),因为编译器可以在f(std::move(a))等情况下自动优化副本,其中f定义为void f(Aa)

到处传递值的一个负面后果是,即使在以下简单情况下,所有代码都会充斥着std::move

void Object::value(A a) 
{
    value_ = std::move(a);
}

显然,如果我只写以下内容:

void Object::value(A a) 
{
    value_ = a;
}

即使没有提示,编译器也应该很难识别a的生命周期即将结束,并且不会用额外的副本来惩罚我。事实上,即使在复杂的函数中,编译器也应该能够识别这一点。

问题:

  1. C++0x标准允许这种优化吗?

  2. 编译器是否使用它?即使在复杂的情况下,即函数由多行组成?

  3. 这种优化的可靠性有多高,即我是否可以期望编译器像我期望编译器应用返回值优化一样利用它?

最佳回答

C++0x标准允许这种优化吗?

Do the compilers employ it? Even in complex cases, i.e. the function consists from more than one line?

How reliable is this optimization, i.e. can I expect the compiler to utilize it as much as I expect the compiler to apply Return Value Optimization?

您应该用打印语句来装饰A(const A&;)A(A&;&;),并运行您感兴趣的测试用例。如果这些用例是您设计的一部分,请不要忘记测试左值参数。

正确的答案将取决于的复制和移动成本,Object::value实际有多少个参数,以及您愿意忍受多少代码重复。

最后,对任何包含“始终”或“无处不在”等词的准则都要非常怀疑。例如,我每隔一段时间就会使用goto。但其他程序员有类似“从不”这样的词与goto联系在一起。但每隔一段时间,你就无法在速度和清晰度上击败goto

有时你应该喜欢一对<code>foo(const a&;)foo(a&;&;)而不是<code>foo(a)

问题回答

暂无回答




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签