gpt4 book ai didi

c++ - 重载具有依赖性的类运算符 new

转载 作者:行者123 更新时间:2023-11-28 05:24:15 24 4
gpt4 key购买 nike

如何在不使用全局变量的情况下提供对类的依赖以便在 operator new 中使用?

如果我理解正确,如果我想在每次有人创建我的类型的实例时自定义行为,那么我必须将 operator new 作为类方法重载。该类方法是静态的,无论我是否将其声明为静态。

如果我有一个类:

class ComplexNumber
{
public:

ComplexNumber(double realPart, double complexPart);
ComplexNumber(const ComplexNumber & rhs);
virtual ~ComplexNumber();

void * operator new (std::size_t count);
void * operator new[](std::size_t count);

protected:

double m_realPart;
double m_complexPart;
};

我想使用我创建的自定义内存管理器来进行分配:

void * ComplexNumber::operator new  (std::size_t count)
{
// I want to use an call IMemoryManager::allocate(size, align);
}

void * ComplexNumber::operator new[](std::size_t count)
{
// I want to use an call IMemoryManager::allocate(size, align);
}

如何在不使用全局变量的情况下使 IMemoryManager 的实例可供类使用?

这对我来说似乎是不可能的,因此迫使类与特定全局实例紧密耦合的不良设计。

最佳答案

这个问题似乎解决了你的问题:C++ - overload operator new and provide additional arguments .为了完整起见,这是一个最小的工作示例:

#include <iostream>
#include <string>

class A {
public:
A(std::string costructor_parameter) {
std::cout << "Constructor: " << costructor_parameter << std::endl;
}
void* operator new(std::size_t count, std::string new_parameter) {
std::cout << "New: " << new_parameter << std::endl;
return malloc(count);
}
void f() { std::cout << "Working" << std::endl; }
};


int main() {
A* a = new("hello") A("world");
a->f();
return 0;
}

输出是:

New: hello
Constructor: world
Working

关于c++ - 重载具有依赖性的类运算符 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com