Question

I am tired of writing std::shared_ptr<MyClass> and std::make_shared<MyClass> and after considering this I would like to find a shorter syntax.

For my short-lived scientific projects I often just need to produce code very quickly and prefer a tight syntax - just don't comment on it ;)

So I though about this:

#define PTR(X) std::shared_ptr<X>
#define NEW(X) std::make_shared<X>

PTR(MyClass) p = NEW(MyClass)(args)

or about this:

template<typename T> using ptr = std::shared_ptr<T>;
template<typename T, typename... Args>
ptr<T> make(Args... args) {
     return std::make_shared<T>(args...);
}

ptr<MyClass> p = make<MyClass>(args);

What do you think are the advantages/disadvantages of theses methods? Is there an even more elegant way?

Was it helpful?

Solution

using std::make_shared; // at file scope, after all #includes
auto p = make_shared<Bob>(a,b,c);

but personally I like the std::.

Using auto is good, because repeating the type twice on the same line is needless noise.

OTHER TIPS

you can use auto

auto p = std::make_shared<MyClass>(args);

What do you think are the advantages/disadvantages of theses methods?

They are awful. It is equivalent to

#define R return

which I have seen, because someone was too lazy to write return.

The problem is that in software development, most time is spent on thinking how to do, and on code maintenance. By using such macros, you are crippling the maintenance, making the maintainer's life more difficult then it should be.

Is there an even more elegant way?

Use a proper IDE, set auto-complete to trigger on one character, and select whatever you need.


Ok, I skipped the template example.

You are introducing new symbols, and writing typedefs to make yourself write less code. The best code is the one not written.

If someone opens your source file, he has also to open the header where you defined those function and template alias. And that increases maintenance cost.

Seeing std::shared_ptr, one knows immediately what it is.

Also, what would you do for std::unique_ptr? Add make1 and ptr1?

Like already mentioned use auto and expand namespaces.

using namespace std;
....

auto allocatedInstance = make_shared<Type>(args);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top