简体   繁体   中英

Explicit modifier for constructors taking reference argument

I read that it's a good practice to define single argument constructors explicit in order to avoid implicit conversions. I understand the pitfall of having int value promoted to class object. I wonder if it also applies to the constructors accepting reference types. How one can provoke implicit conversion in this case:

class Foo
{
public:
    Foo(Bar& bar) { }
};

Does the situation changes if the constructor accepts pointers, is conversion from NULL and nullptr possible ?

class Foo
{
public:
    Foo(Bar* bar) { }
};

Yes to both. A function with signature

void acceptFoo(const Foo& foo)

will make the compiler to create a Foo if you pass a Bar there.

Same for 0 and nullptr .

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