Are there any errors or limitations when smoothing the shared_ptr and unique_ptr patterns?

For a simple reason, cut something like:

std::shared_ptr<...>;
std::unique_ptr<...>;

every time I want to use smart pointers, I thought about using template aliases:

template <typename T> using sptr = std::shared_ptr<T>;
template <typename T> using uptr = std::unique_ptr<T>;

Therefore, I could use them as:

sptr<...>;
uptr<...>;

Assuming I protect them in my own namespace, are there any errors or restrictions when using the template alias with shared / unique_ptr this way? Will I ever be able to do something that I can do with the direct syntax of a template that I cannot with an alias? Is this a bad idea for other reasons?

+4
source share
4 answers

.

std::unique_ptr<T> std::shared_ptr<T> , uptr<T> sptr<T>. :

static_assert(std::is_same<std::shared_ptr<T>, sptr<T>>::value, "");

. "", . , , - .

, , , , . std::unique_ptr . , , , , .

, , , - , ? std::shared_ptr , , sptr . , , " ", . - , , uptr sptr unique_ptr shared_ptr.

(7.1.3)

, typedef, typedef-name. typedef , , 8. , typedef-name . typedef (9.1) .

typedef alias. using typedef-name --seq, . typedef-name. , typedef. , .

+4

, , ,

#include <type_traits>

template <typename T> class A {};
template <typename T> using B = A<T>;

template < template <typename T> class S> class C {};

static_assert( std::is_same< A<int>, B<int> >::value, "same :)"); // they are the same
static_assert( std::is_same< C<A>, C<B> >::value, "not the same :("); // error, not the same

, A B , C<A> C<B> .

+1

a std::shared_ptr<T

template <typename T>
using sptr = std::shared_ptr<T>;

.

- , . , - uptr, uptr unique_ptr.

:

std::unique_ptr<FILE, void (*)(FILE*)> file(fopen("myfile.txt", "r"), [](FILE* f)
                                                                      {
                                                                         fclose(f);
                                                                      });
// use file here to perform input operations
// automatic call to fclose at the end of scope (or any scope exit)

(.. std::default_delete<T>) , FILE*. , FILE* new ed. C-, free delete, deleter delete s, free ing.

uptr<T> , template <typename T> using uptr<T> = ..., template <typename T, typename D = std::default_deleter<T>> using uptr<T, D> = ....

, unique_ptr uptr, .

0

. , , , ? IHMO, , , std::unique_ptr<>, , uptr<>, , ...

, , , , , ( , ). uptr<>, ...


Of course, you can use more descriptive names, for example unique_pointer(suggested in the comments), and use typedefs to implement this through std::unique_ptror, if it is not available, boost::unique_ptr(although if you haven't, std::unique_ptrI would think that you also don't have the semantics of movement and therefore, the whole point is lost unique_pointer). But it will not help , you shorten the input.

-3
source

Source: https://habr.com/ru/post/1568385/


All Articles