Calling a constructor with a member as an argument, parsed as a variable definition

I observed peculiar behavior in g ++ 4.6.3. When creating a temporary call by calling the File(arg) class constructor, the compiler chooses to ignore the existence of arg and parse the expression as File arg;

  • Why is the member name ignored?
  • What does the standard say?
  • How to avoid this? (Without using the new syntax {} )
  • Is there a compiler warning related to this? (I could use an arbitrary string arg, and it would still work quietly)

the code:

 #include <iostream> class File { public: explicit File(int val) : m_val(val) { std::cout<<"As desired"<< std::endl; } File() : m_val(10) { std::cout<< "???"<< std::endl;} private: int m_val; }; class Test { public: void RunTest1() { File(m_test_val); } void RunTest2() { File(this->m_test_val); } void RunTest3() { File(fhddfkjdh); std::cout<< "Oops undetected typo"<< std::endl; } private: int m_test_val; }; int main() { Test t; t.RunTest1(); t.RunTest2(); t.RunTest3(); return 0; } 

Conclusion:

 $ ??? $ As desired $ Oops undetected typo 
+6
source share
1 answer

The compiler considers the line:

 File(m_test_val); 

a

 File m_test_val; 

so you actually create a named object called m_test_val using the default constructor. The same goes for File(fhddfkjdh) .

File(this->m_test_val) solution File(this->m_test_val) - this tells the compiler that you want to use the element to create the created named object. Another would be to name the object - File x(m_test_val) .

+2
source

Source: https://habr.com/ru/post/927726/


All Articles