I was experimenting with template specialisations by recreating a basic std::unique_ptr
when I realised that the following code compiles and runs successfully:
namespace not_std {
template<typename T>
class unique_ptr
{
public:
unique_ptr(T *pointer)
: pointer_(pointer)
{ }
~unique_ptr()
{
delete pointer_;
}
private:
T *pointer_;
};
template<typename T>
class unique_ptr<T[]>
{
public:
unique_ptr(T *pointer)
: pointer_(pointer)
{ }
~unique_ptr()
{
delete[] pointer_;
}
private:
T *pointer_;
};
} // namespace not_std
int main()
{
not_std::unique_ptr<char[]> buffer(char[64]);
}
Note that I'm not looking for feedback on the implementation so I've stripped out irrelevant sections of the class definition.
At first I thought it was a bug in my implementation, but it turns out that even with the standard implementation, this code compiles and runs.
I thought this code would break because char[64]
looks to me like an anonymous stack-allocated array. If this is the case, then it has a lifetime that ends when the constructor for std::unique_ptr
returns. Then wouldn't the destructor be calling delete[]
on stack-allocated memory that is also now out of scope?
Maybe I'm misunderstanding what exactly is happening, since I've never seen this syntax before, where an array T[N]
is directly passed as a parameter.
I appreciate any clarifications/explanations.