Skip to content

Instantly share code, notes, and snippets.

@infotroph
Created August 18, 2017 00:52
Show Gist options
  • Select an option

  • Save infotroph/f9b97127d7c35fc14641bbd891d77328 to your computer and use it in GitHub Desktop.

Select an option

Save infotroph/f9b97127d7c35fc14641bbd891d77328 to your computer and use it in GitHub Desktop.
trying to understand (mis)initialization
struct A{
T x;
A(): x{default_T} {};
A(T t): x{t} {};
};
// Produces two fully initialized A's,
// with a->x == default_T a2->x == my_T.
// Good, fine.
A* a = new A{};
A* a2 = new A{my_T};
// Compiler error: "cannot initialize a variable of type 'A *' with an rvalue of type 'T'".
// I assume direct intialization to a pointer *can't* work here because I'm creating a temporary obect,
// but I do not understand how that relates to the message.
// Question: What does the compiler do with this statement that leads to that error message?
A* a3{my_x};
// Compiles (at least with g++ -std=c++11),
// but segfaults on any attempt to access a4->x
// Questions:
// * Am I correct that the compiler treats this as a declaration and makes no attempt to initialize?
// * For didactic purposes only, is there a way to write this erroneous "initialization" so that it complains at compile time?
A* a4{};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment