Function-style cast vs. constructor

吃可爱长大的小学妹 提交于 2021-02-07 05:39:04

问题


I learned that in C++,

typedef foo* mytype;

(mytype) a        // C-style cast

and

mytype(a)         // function-style cast

do the same thing.

But I notice the function-style cast share the same syntax as a constructor. Aren't there ambiguous cases, where we don't know if it is a cast or a constructor?

char s [] = "Hello";
std::string s2 = std::string(s);     // here it's a constructor but why wouldn't it be ...
std::string s3 = (std::string) s;    // ... interpreted as a function-style cast?

回答1:


Syntactically, it is always a cast. That cast may happen to call a constructor:

char s [] = "Hello";
// Function-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s2 = std::string(s);
// C-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s3 = (std::string) s;



回答2:


Conversion is a form of initialization. When a type is implicitly convertible to another, a functional cast is a form of direct initialization. The compiler knows which types are convertible.

Whenever something is converted to a class type, either a converting constructor of the target type or a conversion operator of the source type is used. In your examples, both casts call the default constructor.




回答3:


The compiler knows. And it calls the constructor when there is one in both cases.



来源:https://stackoverflow.com/questions/45505861/function-style-cast-vs-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!