简体   繁体   English

RVO,移动语义和争取最佳代码的斗争

[英]RVO, move semantics and the struggle towards optimal code

If I get it correctly, move semantics allows to move and reuse resources from temporary, unnamed objects. 如果我正确地得到它,移动语义允许从临时的,未命名的对象移动和重用资源。 RVO, albeit preceding move semantics goes further and "steals" the entire object to avoid the extra constructor call and assignment/copy function. RVO虽然先前的移动语义更进一步,但“窃取”整个对象以避免额外的构造函数调用和赋值/复制函数。

This seems a bit counter intuitive to me, wouldn't it be that much faster, simple and user obvious if the called constructor uses directly the address of the final lvalue target to directly emplace data where the user needs it? 这对我来说似乎有点反直觉,如果被调用的构造函数直接使用最终左值目标的地址直接将数据放在用户需要的地方,那么它会不会更快,更简单,用户更明显?

I mean, "create this object in this location" seems a bit more intuitive than "create this object somewhere, then copy it to its right location". 我的意思是,“在这个位置创建这个对象”似乎比“在某处创建这个对象,然后将其复制到正确的位置”更直观。

Yes it is "a bit counter intuitive". 是的,它“有点反直觉”。 With copy elision enabled all side effects of the constructor are elided, too. 启用复制省略后,构造函数的所有副作用也会被删除。

#include <iostream>

struct X {
    X() { std::cout << "Construct" << std::endl; }
    X(X&&) { std::cout << "Move" << std::endl; }
    ~X() { std::cout << "Destruct" << std::endl; };
};

X f() { return X(); }

int main()
{
    X x(f());
    return 0;
}

Copy elision: g++ -std=c++11 src-test/main.cc 复制省略:g ++ -std = c ++ 11 src-test / main.cc

Construct
Destruct

No copy elision: g++ -std=c++11 -fno-elide-constructors src-test/main.cc 没有副本省略:g ++ -std = c ++ 11 -fno-elide-constructors src-test / main.cc

Construct
Move
Destruct
Move
Destruct
Destruct

The compiler, knowing the hardware the program/library is build for, is able to apply (optional) copy elision. 知道构建程序/库的硬件的编译器能够应用(可选)复制省略。 The C++ language, itself, is not aware of hardware specific return mechanisms. C ++语言本身并不了解硬件特定的返回机制。 Hence it is not possible to construct at a certain address in this context. 因此,在这种情况下不可能在某个地址构建。

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

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