Nov 23, 2017 at 5:27pm Nov 23, 2017 at 5:27pm UTC
Second part of the answer: Since your func2() returns a reference, you have to initialize f2. All references should be initialized at creation.
Nov 24, 2017 at 3:31am Nov 24, 2017 at 3:31am UTC
const int & func2() { const int i {2}; return i; }
This engenders undefined behaviour.
Nov 24, 2017 at 3:33am Nov 24, 2017 at 3:33am UTC
yeah, you're right i think
Nov 26, 2017 at 10:11pm Nov 26, 2017 at 10:11pm UTC
Hi
thanks for the replies, so as long as the variables to functions that return a reference are initialised it compiles, something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <iostream>
#include <typeinfo>
const int func1();
const int & func2();
struct X { double d; };
auto main() -> int {
int i{0};
const X* x = new X();
decltype (func1()) f1;
decltype (func2()) f2 = f1;
decltype (i) i1;
decltype (x->d) d1;
decltype ((x->d)) d2 = d1;
std::cout << "Declare type func1() " << f1<< "\n" ;
std::cout << "Declare type func2() " << f2<< "\n" ;
std::cout << "Declare type i " << i1 << std::endl;
std::cout << "Declare type d1 " << d1 << std::endl;
std::cout << "Declare type d2 " << d2 << std::endl;
return 0;
}
const int func1() {
return 1;
}
const int & func2() {
int temp{2};
int * n = new int ;
*n = temp;
return *n;
}
I understand f1 & f2, but I don't understand the following 2 declarations:
1 2
decltype (x->d) d1;
decltype ((x->d)) d2 = d1;
which occur on page 12 of the book. Firstly , what is "d", and secondly
why do I have to initialise " decltype((x->d)) d2" to d1 in order for the code to compile ?
Last edited on Nov 26, 2017 at 10:12pm Nov 26, 2017 at 10:12pm UTC
Nov 26, 2017 at 10:43pm Nov 26, 2017 at 10:43pm UTC
Last edited on Nov 26, 2017 at 10:44pm Nov 26, 2017 at 10:44pm UTC