为什么定义全局 `void operator new(std::size size)` 不会导致多重定义链接错误?

问题描述 投票:0回答:1

为什么在全局范围定义

void* operator new(std::size_t)
不会导致多重定义链接错误?

例如下面的代码编译并运行,但我想 libstdc++ 必须定义一个具有相同名称和签名的全局范围函数,不是吗?

// main.cpp

#include <iostream>
#include <new>

void* operator new(std::size_t size) {
    std::cout << "Custom new called for size: " << size << " bytes" << std::endl;

    // Call malloc to allocate memory.
    void* ptr = std::malloc(size);

    return ptr;
}

int main() {
    int* p = new int;
    double* q = new double[10];

    delete p;
    delete[] q;

    return 0;
}
$ g++ --version && g++ -g ./main.cpp && ./a.out
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Custom new called for size: 4 bytes
Custom new called for size: 80 bytes
c++ operator-overloading new-operator multiple-definition-error
1个回答
1
投票

全局命名空间范围内的函数重载

void* operator new(std::size_t)
具有特殊属性,它是可替换的全局分配函数之一。这些函数和可替换的全局释放函数遵循与任何其他函数不同的规则。

它们是由 C++ 实现定义的,但同时允许用户在程序中的任何位置用自己的定义替换它们,在这种情况下,程序中将忽略默认实现。这种行为对于任何其他功能来说都是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.