Giter VIP home page Giter VIP logo

Comments (5)

pezy avatar pezy commented on July 19, 2024 3

从语义上讲,应该是触发 移动构造函数。但移动语义是在 C++ 11 之后引入的,所以在此之前,将表现为 拷贝构造函数

vs2008 不支持 C++11,所以会触发拷贝构造。如果在 String 类定义中加上:

String(String &&) noexcept;
String& operator=(String&&) noexcept;

那么在 VS2012, 2013, 2015 中,将触发移动构造。

以上是 Visual Studio 系编译器的行为,还是比较真实的还原了标准所规定的语义的。


然而 Mingw 算是 GCC 在 Windows 上实现的简版,属于 GCC/Clang 系的编译器风格。

这类编译器对于这种情况,会默认进行优化,使得无论拷贝构造还是移动构造,都不会被触发。(因为它能够识别出来这是一个临时对象,用不着拷贝,连移动也可以省了。)

这种优化有一个专有名词,我们称之为"返回值优化 RVO"。你可以点击链接查看更多细节。

如果你想禁用这种优化,可以在编译的时候加上一个 flag:-fno-elide-constructors。编译器的表现就会符合语义逻辑了。

from cppprimer.

husy8 avatar husy8 commented on July 19, 2024 1

@pezy 最新的VS2015.1默认也会进行“返回值优化”,根据维基百科的示例:

#include <iostream>
struct C {
    C() {}
    C(const C&) { std::cout << "A copy was made.\n"; }
};

C f() {
    return C();
}

int main() {
    std::cout << "Hello World!\n";
    C obj = f();
    return 0;
}

在VS2015.1内编译运行,只显示了Hello World!而没有A copy was made.
image
VS2015.1我只更改了主题、字体,其他保持原样。

from cppprimer.

xyz4826757 avatar xyz4826757 commented on July 19, 2024

谢谢,感觉还有好多东西要学习

from cppprimer.

pezy avatar pezy commented on July 19, 2024

@wtlusvm 谢谢提醒与补充。

VS2015.1 开始,开始接纳 Clang 了

所以一些行为也越来越一致。

from cppprimer.

husy8 avatar husy8 commented on July 19, 2024

原来如此!谢谢!

from cppprimer.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.