What is an Implicit Conversion?
Reading about smart pointers and it constantly mentions that the explicit keyword prevents. Prevents what?
regards
ace
When designing classes, if you have a constructor that accepts an argument of a particular type, the compiler will interpret that as a means of casting the indicated type to an instance of your new type. An example will help:
*** The constructor listed here is interpreted by the compiler as a means of casting an int to a MyHugeInt. This will happen automatically, even if it''s not something you (as the writer of MyHugeInt) intends. Thus, the following code will compile:
MyHugeInt i = 5;
The 5 is converted into a temporary MyHugeInt object, and then the copy constructor is called.
The "explicit" keyword prevents such casting from happening if it''s not something you want.
With smart pointers, an explicit keyword on a constructor like:
the intention is usually to prevent a value of T* to be cast up to a smart pointer object.
Regards,
Jeff
[ CodeDread ]
class MyHugeInt { // some implementation here...public: MyHugeInt(); // default constructor MyHugeInt(const MyHugeInt& o); // copy constructor MyHugeInt(int v); // ***};
*** The constructor listed here is interpreted by the compiler as a means of casting an int to a MyHugeInt. This will happen automatically, even if it''s not something you (as the writer of MyHugeInt) intends. Thus, the following code will compile:
MyHugeInt i = 5;
The 5 is converted into a temporary MyHugeInt object, and then the copy constructor is called.
The "explicit" keyword prevents such casting from happening if it''s not something you want.
With smart pointers, an explicit keyword on a constructor like:
template<typename T>class MySmartPtr { T* ptr;public: explicit MySmartPtr(T*);};
the intention is usually to prevent a value of T* to be cast up to a smart pointer object.
Regards,
Jeff
[ CodeDread ]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement