使用clang和gcc编译时,代码不调用Move构造函数(Code not calling Move constructor when compiled with clang and gcc)

编程入门 行业动态 更新时间:2024-10-25 17:29:16
使用clang和gcc编译时,代码不调用Move构造函数(Code not calling Move constructor when compiled with clang and gcc)

所以,这在GCC,CLANG和MSVC上编译得很好但是给出了不同的输出:

#include <iostream> using namespace std; class A { public: A() { cout << this << " def" << endl; } A(const A&) { cout << this << " copy" << endl; } A(A&&) { cout << this << " move" << endl; } A& operator= (const A&) { cout << this << " copy=" << endl; return *this; } A& operator= (A&&) { cout << this << " move=" << endl; return *this; } ~A() { cout << this << " ~A" << endl; } }; A f() { A a; return a; } int main(){ A a = f(); }

使用GCC和CLANG输出:

0xbfad67cf def 0xbfad67cf~A

虽然MSVC输出正如预期(C ++ 11标准):

0039FA3B def 0039FA3B移动 0039FA3B~A

因此,使用MSVC调用的代码调用移动构造函数,而使用GCC和CLANG移动构造函数则不会调用。 我也试过禁用优化,仍然得到相同的输出。 更奇怪的是,当我改变f()以返回A()时,即使在MSVC上也不会调用移动构造函数。

编译器版本:

gcc:版本4.7.2(GCC) clang:版本3.2(标签/ RELEASE_32 / final)目标:i386-pc-linux-gnu

平台: Linux / ArchLinux

So, this compiles just fine on GCC, CLANG and MSVC but gives different output:

#include <iostream> using namespace std; class A { public: A() { cout << this << " def" << endl; } A(const A&) { cout << this << " copy" << endl; } A(A&&) { cout << this << " move" << endl; } A& operator= (const A&) { cout << this << " copy=" << endl; return *this; } A& operator= (A&&) { cout << this << " move=" << endl; return *this; } ~A() { cout << this << " ~A" << endl; } }; A f() { A a; return a; } int main(){ A a = f(); }

With GCC and CLANG outputs:

0xbfad67cf def 0xbfad67cf ~A

While with MSVC out is as expected (C++11 standard):

0039FA3B def 0039FA3B move 0039FA3B ~A

So, code compiled with MSVC calls move constructor, while with GCC and CLANG move constructor is not called. I also tried with optimizations disabled, and still get the same output. What is more strange is that when I change f() to return A(), move constructor is not called even on MSVC.

Compiler versions:

gcc: version 4.7.2 (GCC) clang: version 3.2 (tags/RELEASE_32/final) Target: i386-pc-linux-gnu

Platform: Linux/ArchLinux

最满意答案

那就是返回值优化

http://en.wikipedia.org/wiki/Return_value_optimization

编译器优化的返回对象不是被复制而是被移除

That is return value optimization

http://en.wikipedia.org/wiki/Return_value_optimization

compiler optimized returned object not to be copyed than removed

更多推荐

本文发布于:2023-07-30 07:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   代码   Move   clang   gcc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!