【问题标题】:bug of feature of g++ linker [duplicate]g ++链接器功能的错误[重复]
【发布时间】:2016-09-29 05:10:08
【问题描述】:

我有 3 个文件

测试.h

#pragma once
#include <memory>
std::unique_ptr<int> createInt();

test.cpp - 注意 test.h 不包括在内

#include <memory>

std::shared_ptr<int> createInt()
{
    return std::make_shared<int>();
}

main.cpp

#include "test.h"
int main()
{
    createInt();
    return 0;
}

它编译没有任何问题 g++ -Wall -Wextra main.cpp test.cpp
并在运行时失败:

./a.out
a.out(3632,0x7fff78ba9300) malloc: *** error for object 0x7fe290404c68: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

但是 Visual Studio 不会编译此类源代码并出现 LNK1120 错误。

为什么 g++ 链接器不会失败这样的代码?

【问题讨论】:

    标签: c++ g++


    【解决方案1】:

    返回类型不是重载决议签名的一部分,只有名称和参数类型。它在 C++ 规范中。

    编译器将发出对名为createInt 的不带参数的函数的引用,链接器将找到这样的符号。

    返回类型不匹配会导致运行时未定义的行为

    【讨论】:

    • 我明白这一点。但为什么要这样做呢?在我看来,这是一种奇怪且错误导向的方法。正如我在 Visual Studio 中所写,返回类型是签名的一部分。
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2012-06-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多