user1899020
user1899020

Reputation: 13575

Is this a good practice to rename and reinclude std::unique_ptr?

The code is as following

// in ptr.h
#pragma once
#include <memory>
template<class T> using Ptr = std::unique_ptr<T>;

So every time I use std::unique_ptr, I include "ptr.h" and use it as Ptr. Is this a good practice?

Upvotes: 0

Views: 379

Answers (2)

Mark Garcia
Mark Garcia

Reputation: 17708

Suppose your requirements have changed and decided to use std::share_ptr. You would naturally do:

template<class T> using Ptr = std::shared_ptr<T>;

OK! Great! No change in your code that uses Ptr. But std::shared_ptr is semantically different from std::unique_ptr. When some unknowing programmer who doesn't know of the change continues to think that Ptr is still std::unique_ptr... kaboom!

One thing I learned is that it is important not to sacrifice code readability just for the sake of being brief.

Upvotes: 2

Doug T.
Doug T.

Reputation: 65649

This kind of thing only hurts readability. The odds are higher that the average C++ programmer will know what a unique_ptr is before they know what your notion of Ptr is. Moreover I can google the former and not the latter.

Upvotes: 6

Related Questions