Weak script constructors weak_ptr

the following two weak_ptr constructors are: http://msdn.microsoft.com/en-us/library/bb982126.aspx

weak_ptr(const weak_ptr&); template<class Other> weak_ptr(const weak_ptr<Other>&); 

valid code (from memory ):

 weak_ptr(const weak_ptr& _Other) { // construct weak_ptr object for resource pointed to by _Other this->_Resetw(_Other); } template<class _Ty2> weak_ptr(const weak_ptr<_Ty2>& _Other, typename enable_if<is_convertible<_Ty2 *, _Ty *>::value, void *>::type * = 0) { // construct weak_ptr object for resource pointed to by _Other this->_Resetw(_Other); } 

Q1: Why does the top copy constructor even exist? It seems that the lower part takes into account each case (including the upper). Is he even called? and if they did not turn it on, then the lower part will take place?

Q2: What happens to the second argument to the bottom (templated) constructor. I think I understand the SFINAE aspect, but I don't understand why there are additional * after ::type

+4
source share
2 answers

Q1) If you are not writing a copy constructor, the compiler will generate one for you, which is not the way you want. Template conversion constructors are not taken into account.

Q2) Remember that shared_ptr<T> is similar to T* , convertibility should be checked at the pointer level. If T* can be converted to U* , then you can assign it to another. Think of pointers to the database. [Sorry, this was not what you requested.] The final type of argument just needs to exist, but we also don’t want to specify the argument itself. A universal way to create a type for which we can also provide a default argument is a pointer. In short, we need to make the function depend on a type that may or may not exist, but without requiring the user to know about it.

+5
source

Re Q1: The template constructor is never a copy constructor, even if it manages to copy. if a custom "copy constructor" is not defined, then the compiler will generate it as needed.

Re Q2: second argument, defaults to 0 by default, this is just a place to place enable_if . you can find out more about this (if I remember correctly) in the Boost documentation.

Cheers and hth.,

+3
source

All Articles