0

In the code below, I thought that, if I simply forget to return something, it'd simply return the default std::shared_ptr<int> which should be an empty pointer, or a pointer equal/that points to nullptr.

#include <stdio.h>
#include <memory>
#include <iostream>
std::shared_ptr<int> s() {

}

int main(void) {
  auto a = s();
  if (a) {
    std::cout << "has something" << std::endl;
  } else {
    std::cout << "has nothing" << std::endl;
  }
}

However running it gives me "illegal instruction", which I think it's undefined behaviour.

Why simply C++ does not enforce me to return something if it fails to assing a default value for the returned value? This is pretty dangerous.

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1) It is UB *only* if the caller attempts to use the return value. 2) There is a special exception for `main` where a missing return translates to an implied `return 0;`. – dxiv Sep 17 '20 at 03:00
  • 1
    "*Why simply C++ does not enforce me to return something if it fails to assing a default value for the returned value? This is pretty dangerous.*" How would that be any less dangerous? If the code is designed for that value to be returned, it would simply return it. Having the implementation return a value you don't expect is just as dangerous. – David Schwartz Sep 17 '20 at 03:01
  • Most compilers will emit a warning in such a case, if your settings are adequate. – Etienne de Martel Sep 17 '20 at 04:03

0 Answers0