Reputation: 90
I'm trying to build my own Smart Pointer that will allow me to declare it like so:
SmartPtr<MyClass> ptr = new MyClass;
I want the constructor to be explicit so I made it like so:
template<class T>
class SmartPtr
{
public:
SmartPtr();
explicit SmartPtr(T* _ptr);
explicit SmartPtr(const SmartPtr& other);
}
However, when I try to declare it as I mentioned on top, I get the following error:
error: conversion from ‘MyClass*’ to non-scalar type ‘SmartPtr<MyClass>’ requested
I know the error is because the copy CTOR has a special syntax with '=' and a conversion CTOR cannot be declared in that method. My question is, is there any method to keep the required syntax I mentioned above, and have an explicit CTOR?
Upvotes: 1
Views: 391
Reputation: 136525
My question is, is there any method to keep the required syntax I mentioned above, and have an explicit CTOR?
Probably not. That syntax is copy initialization and it requires a non-explicit constructor.
Note that the copy constructor does not need to be explicit. If it is explicit then you won't be able to pass SmartPtr
to a function that accepts it by value.
Another way to construct your pointer with minimum syntax overhead is to add a factory function and use it like:
template<class T>
SmartPtr<T> make_ptr(T* p) {
return SmartPtr<T>{p};
}
auto ptr = make_ptr(new MyClass);
Or, something akin to std::make_shared<>
:
auto ptr = make_ptr<MyClass>();
Upvotes: 1