简体   繁体   中英

constructor call or function-style cast in C++

If I have the following c++ code:

class foo{
public:
    explicit foo(int i){};
};
void f(const foo &o){
}

And then I call

f(foo(1));

Is foo(1) constructor call or function-style cast?

他们是一样的东西。

它是一个函数式转换,导致构造函数调用,所以两者都是。

5.2.3 Explicit type conversion (functional notation)

1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). ...

Your code creates a temporary, using the constructor you have with the argument's value 1, and binds it to a const reference. The temporary's lifetime ends at the end of the statement where it was created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM