Created
August 18, 2017 00:52
-
-
Save infotroph/f9b97127d7c35fc14641bbd891d77328 to your computer and use it in GitHub Desktop.
trying to understand (mis)initialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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