简体   繁体   English

std :: ofstream在全局运算符中新

[英]std::ofstream in global operator new

Is there a way to write to a file within a replaced global operator new? 有没有办法在新的替换的全局运算符中写入文件?

// simple operator new replacment
void* operator new(std::size_t bytes) {
    std::ofstream log{"log.txt"};
    log << bytes << " bytes allocated\n";
    return std::malloc(bytes);
}

std::ofstream uses new, creating an infinite loop. std :: ofstream使用new,创建一个无限循环。

You can overload the operator but for specific parameters, I mean not the global one, Here an example for a class called student : 您可以重载运算符,但对于特定的参数,我的意思不是全局的,这里是一个名为Student的类的示例:

 void * operator new(size_t size)
{
    cout<< "Overloading new operator with size: " << size << endl;
    void * p = ::new student(); 
    //void * p = malloc(size); will also work fine

    return p;
}

you can find more details Here 您可以在此处找到更多详细信息

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

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