在不提供名称的情况下声明类型

Ole*_*leg 2 c++ compiler-optimization

我在调试模式下测试了gcc上的一些代码,但不确定它是否适用于其他编译器.
我的问题是任何编译器将如何优化以下c ++代码(make_auto宏):

class A
{
private:
 void *ptr;
public:
  A(void* _ptr) {ptr = _ptr;}
  ~A() {free(ptr);}
};

#define make_auto(ptr) A(ptr)

int main ()
{
   char *a = (char*)malloc(sizeof(char)),*b = (char*)malloc(sizeof(char));
   make_auto(a);
   make_auto(b);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

它总是会调用A的构造函数和析构函数吗?或者编译器会在任何情况下优化此代码并删除A(ptr)调用,因为它可以认为它不会被更多地使用.

UPD:

我知道boost和std :: auto_ptr.我有自己的内存管理器控制内存碎片,有助于避免内存泄漏.现在我想"教"我的内存管理器创建auto_ptrs,就像它在boost和stl中做的那样.

UPD2:

这是完整的代码,我正在使用,我认为是正确的:

    class AutoPtr
    {
    private:
        void *ptr;
        Application *app;
    public:
        AutoPtr(Application *_app,void *a)
        {
            printf("constructor called\n");
            ptr = a;
            app = _app;
        }
        ~AutoPtr()
        {
            fast_free(app,ptr);
            printf("destructor called\n");
        }

    };
#define make_auto_ptr(app,ptr)  AutoPtr(app,ptr)
    static void AutoPtrTest1()
    {
        test_declare_app

        char *a = fast_alloc(app,char,20);
        char *b = fast_alloc(app,char,11);

        {
            make_auto_ptr(app,a);
            make_auto_ptr(app,b);
        }


        test_free_app
        printf("Autoptrtest1 passed\n");                
    }
Run Code Online (Sandbox Code Playgroud)

输出:

构造函数名为析构函数,称为构造函数,名为destructor,名为Autoptrtest1

所以它不正常,因为我想(我没有检查析构函数调用).但它像我之前所说的那样两次调用构造函数.如何更改make_auto_ptr以自动声明auto-ptrs?

Joh*_*itb 7

没有任何事情发生,因为你的代码是不正确的.A(a);A(b);声明ab.由于a已经声明,并且A在任何情况下都没有默认构造函数,编译器应发出诊断信息.

如果你解决这些问题,那么编译器被允许优化掉这些,如果mallocfree你使用的是标准的库函数,因为该代码真的有没有明显的副作用.

优化编译器应该知道的特殊意义mallocfree,我也不会惊讶地看到它优化这个了.但无论出于何种原因,我还可以想象编译器不会优化它.它实际上取决于您的编译器及其使用的标志,但标准肯定允许它在这里进行优化.

这是clang -O2 -emit-llvm -S main1.cpp -o -输出的代码:

define i32 @main() nounwind {
  ret i32 0
}
Run Code Online (Sandbox Code Playgroud)

  • @Oli我觉得你错过了什么.如何`A(a);`不等同于'A a;`? (3认同)