Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Calling allocator.construct for Primitives

Is it necessary for me to call allocator.construct() for an array of primitive types allocated using an arbitrary allocator, as in the code listing below? The class doesn't require the allocated memory to be initialized to any particular value, so it seems to me that calling allocator.construct() with a newly-allocated chunk of memory would be unnecessary. Is there any danger in not calling this method, given that the array always consists of primitive types?

template <class T, template <class> class Allocator = std::allocator>
class foo
{
public:
    typedef Allocator<T> allocator;
    typedef typename allocator::pointer pointer;
private:
    unsigned size_;
    allocator alloc_;
    pointer t_;
public:
    foo(unsigned n) throw(std::bad_alloc) : size_(n), alloc_(),
    t_(alloc_.allocate(n))
    {
        // Note that I do not call alloc_.construct() here.
    }

    ~foo() { alloc_.deallocate(t_, size_); }
};
like image 352
void-pointer Avatar asked Jan 24 '26 12:01

void-pointer


1 Answers

Yes. The allocator is free to impose whatever custom book-keeping it wants, including the number of existing objects. There is no guarantee at all that it simply does new (memory) T(...). And in addition, it would be a very nasty surprise for a person to change your code so that it's no longer just primitives and then find it randomly breaks sometime later.

like image 100
Puppy Avatar answered Jan 26 '26 02:01

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!