fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. // minimap example-class to test
  5. // - constructor variable shadowing
  6. // - assigning to const-refs -- see https://stackoverflow.com/questions/27423364/binding-const-of-temporary-no-compiler-warning
  7.  
  8. // the device-under-test:
  9. class TestClass {
  10. public:
  11. std::string a;
  12. std::string b;
  13. const std::string &c;
  14. // removing the "reference" whould remove the temporary-problem
  15. const std::string &d;
  16.  
  17. TestClass(std::string a, std::string b, const std::string &c,
  18. const std::string &d)
  19. : a(a), b(b), c(c), d(d) {
  20. // pitfall: changing the variable "a" from the constructor-call, not
  21. // the actual member variable
  22. a = "A";
  23. // using pointer-indirection the lookup-semantics are different and the
  24. // member variable is found instead
  25. this->b = "B";
  26. // "c" is a const-ref, cannot be changed at all... if it is assigned some
  27. // temporary value it is mangled up...
  28. }
  29. };
  30.  
  31. int main() {
  32.  
  33. // a stack-resident variable, where we can safely pass a const-ref
  34. std::string c("c");
  35. // creating the actual test-oject.
  36. //
  37. // NOTE: the fourth variable "d" is a
  38. // temporary, whose reference is not valid... what I don't get in the
  39. // moment: why does no compiler warn me?
  40. TestClass dut("a", "b", c, "d");
  41.  
  42. // and printing what we got:
  43. std::cout << "beginning output:\n\n";
  44. std::cout << "dut.a: '" << dut.a << "'\n";
  45. std::cout << "dut.b: '" << dut.b << "'\n";
  46. std::cout << "dut.c: '" << dut.c << "'\n";
  47. // this will abort the program (gcc-4.9.1) or be an empty string
  48. // (clang-3.5) -- don't know whats going on here... I mean I know why
  49. // it should segfault (using reference of temporary), but why does no
  50. // compiler warn here?
  51. //std::cout << "dut.d: '" << dut.d << "'\n";
  52. std::cout << "\nthats it!\n";
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
beginning output:

dut.a: 'a'
dut.b: 'B'
dut.c: 'c'

thats it!