当前位置: 首页 > 工具软件 > Elide > 使用案例 >

-fno-elide-constructors 构造函数编译器优化

谢旻
2023-12-01

看到网上的一段测试移动构造函数的代码,如下,结果只走了默认构造函数

#include <iostream>

class A {
    public:
        A() {
            std::cout << "default Constructor" << std::endl;
        }
        A(const A&) {
            std::cout << "copy Constructor" << std::endl;
        }
        A(A &&) {
            std::cout << "move Constructor" << std::endl;
        }
        void f() const{
            std::cout << "ffff" << std::endl;
        }

        A & operator=(const A & a ) {
            std::cout  << "operator = &" << std::endl;
            return *this;
        }
        A& operator=(A && a) {
            std::cout << "operator = && "  << std::endl;
            return *this;
        }
};

A getA() {
    A a;
    return a;
}

int main() {
    A b = getA();
    return 0;
}

输出如下:


%: clang++ ./rightreftest.cpp -o test --std=c++11
%: ./test
default Constructor

这不符合我们的理解,getA函数内部存在一次默认构造,应该在main内部还存在移动构造函数。

调查发现,需要添加 -fno-elide-constructors 关闭编译器构造优化

%: clang++ ./rightreftest.cpp -o test --std=c++11 -fno-elide-constructors
%: ./test
default Constructor
move Constructor
move Constructor

-fno-elide-constructors 选项

   -fno-elide-constructors
       The C++ standard allows an implementation to omit creating a
       temporary which is only used to initialize another object of the
       same type.  Specifying this option disables that optimization, and
       forces G++ to call the copy constructor in all cases.
 类似资料: