0

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?

user1899020
  • 11,941
  • 15
  • 66
  • 130

2 Answers2

6

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.

Doug T.
  • 59,839
  • 22
  • 131
  • 193
  • Ptr is short and the user can check its definition like a code using its own classes. – user1899020 Feb 01 '13 at 02:15
  • 7
    @user1899020: Anything can be checked, given enough time. The question is whether you're *helping* anyone (but yourself). Remember that code is very cheap to write, but extremely expensive to read. – Kerrek SB Feb 01 '13 at 02:16
  • 1
    @user1899020 it gets even more confusing when some dummy like me comes to work on your code and uses `unique_ptr` instead of `Ptr`. Now your code is doubly confusing. – Doug T. Feb 01 '13 at 02:46
  • 1
    @user1899020: Are you asking a question or making a statement? This style of code is terrible, sorry. Who cares if it's short, you only type it once. You read it over and over. I want to read what it is. – GManNickG Feb 01 '13 at 05:05
2

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.

Mark Garcia
  • 16,438
  • 3
  • 50
  • 93