3

I have 3 files

test.h

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

test.cpp - pay attention test.h wasn't included

#include <memory>

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

main.cpp

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

It compiles with out any problems with g++ -Wall -Wextra main.cpp test.cpp
And fails in runtime:

./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

However Visual studio doesn't compile such source with LNK1120 error.

Why g++ linker doesn't fail such code?

Andrey Nekrasov
  • 456
  • 2
  • 12

1 Answers1

2

Return-type is not part of the signature for overload resolution, only name and argument types. It's in the C++ specification.

The compiler will emit a reference to a function named createInt taking no arguments, and the linker will find such a symbol.

The return-type mismatch will lead to undefined behavior at run-time.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I understood this. But why was it done so? In my opinion this is strange and error leading approach. As I wrote in Visual studio return-type is a part of the signature. – Andrey Nekrasov May 31 '16 at 09:20