1

A class A is defined and implemented. Later it's declared as a struct as the template argument of std::unique_ptr. The compiler(g++10.1) complains nothing about it and the program can be run.

#include <iostream>
#include <string>
#include <memory>

class A
{
public:
    std::string info = "Hello World!";
};

int main()
{
    std::unique_ptr<struct A> a{new A};
    std::cout << a->info << "\n";
    return 0;
}

If I define a without the new A

std::unique_ptr<struct A> a;

The code can still be compiled but there is a segmentation fault during runtime. So why is this possible?

taotsi
  • 354
  • 2
  • 11
  • `std::unique_ptr a;` without the `new` creates a `unique_ptr` that points to `nullptr`, so why do you expect that this should not result into runtime problems at `a->info`? – t.niese Aug 04 '20 at 11:18
  • See also [What are the differences between struct and class in C++?](https://stackoverflow.com/questions/92859/what-are-the-differences-between-struct-and-class-in-c) Brief answer: almost none. – Igor G Aug 04 '20 at 11:23
  • Note that `A` is automatically `typedef`ined so you don't have to use `struct` or `class` to declare variables of `A`. Just: `std::unique_ptr a = std::make_unique();` – Ted Lyngmo Aug 04 '20 at 12:07

1 Answers1

1

It's allowed to mix class and struct in a declaration, it's only an issue in a definition of a class. Refer to Mixing class and struct for more details.

The seg fault in the second case comes from null pointer access, a form of undefined behavior.

std::unique_ptr<struct A> a; initializes a to an "empty" state. Then a->info will access a null pointer, which in your case causes a seg fault.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Dereferencing a null pointer causes undefined behaviour. One possible outcome of undefined behaviour is a seg fault. There are many other possible outcomes though - it is, for example, quite possible that the OPs code - when built with a different compiler, or even run on a machine with more memory - will run without any symptoms. – Peter Aug 04 '20 at 11:46