简体   繁体   中英

C++ constructors during function calls

In C++ when you have an object that is passed to a function by value the copy constructor is invoked. Such as in this function signature:

void foo(Object o);

A couple years ago someone told me that you can pass arguments that fit the constructor of an object that is an argument to a function. So, using the above function signature foo, let's say Object has the constructor:

Object(int a, int b);

we would be able to call the function foo like this:

foo(1,2);

I haven't been able to find any information about this and I think that I either misinterpreted what I heard years ago or that the person was just wrong. Is there any way to do this other than:

foo(Object(1,2));

and if not, is there a reason that this constructor can not be implicitly invoked during a function call?

A couple years ago someone told me that you can pass arguments that fit the constructor of an object that is an argument to a function.

If you recall it right, what was said is wrong.

Given your function and class, you may not use:

f(1, 2);

However, you may use:

f({1, 2});

The {...} will call an appropriate constructor, if one matches.

As a matter of personal preference, I would still use:

f(Object{1, 2});

IMO, the intent is more clearly expressed when using Object{1, 2} than when using just {1, 2} .

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