Difference between dispenser supplied as template parameter and dispenser supplied as constructor argument in C ++ containers?

What is the difference between the delivery of an STL container (e.g. std :: vector) with a dispenser as a template parameter, for example:

std::vector<int, std::allocator<int>> some_ints;

and providing a allocator as an argument to the constructor, for example:

std::allocator<int> temp;
std::vector<int> some_ints(temp);

and what are the advantages either, given that they are not the same thing (i.e., one supplies the type, another instance of the type) and can be used separately from each other?

+3
source share
2 answers

Can be used separately from each other?

template . . .

template<typename Type> f(Type instance); , Type instance, . , , , /.

( ++ 11)

vector:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

:

explicit vector( const Allocator& alloc = Allocator() );

Allocator alloc. . Allocator. , , , , Allocator, Allocator ( , , , , ).

-, Allocator, , , .

, , vector, - DerivedAllocator, Allocator, . , :

vector<T> v( DerivedAllocator<T>() );

.

Allocator, ?

- , ( ). : SRamAllocator, RamAllocator ..

. , - , , , . . , , "", free ing. new/delete.

Allocator, ?

. , . . - " ". , , CPU/.

, , .

, , .

. pre-++ 11 , . Allocator, . Allocator() .

, , ... . , ( ).

+5

.

.

; .

; - , - . .

:

// N.B. I've included one non-defaulted argument to match
// the vector example, but you could omit `T1` entirely and
// write e.g. `Foo<> obj4`.
template <typename T1, typename T2 = int>
struct Foo
{
   Foo(T2 x = 42) : x(x) {}

private:
   T2 x;
};

int main()
{
   Foo<char, int> obj1;      // like your first example
   Foo<char>      obj2(42);  // like your second example
   Foo<char>      obj3;      // this is more common

   // obj1, obj2 and obj3 are not only of identical type,
   // but also have identical state! You just got there
   // in different ways.
}
+1

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


All Articles