Functional casting vs constructor

I found out that in C ++,

typedef foo* mytype;

(mytype) a        // C-style cast

and

mytype(a)         // function-style cast

do the same thing.

But I notice that the style function uses the general syntax as a constructor. Are there any ambiguous cases when we do not know if this is a throw or a constructor?

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

Syntactically it is always . This cast may cause a constructor call:

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;
+10
source

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

, - , , . .

+1

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

-1
source

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


All Articles