C ++: saving a class instance in allocated memory

I have a class A. Some library that I use allocates for me a certain amount of memory sizeof A and returns a pointer to void.

A* pObj = (A*) some_allocator_im_forced_to_use( sizeof A );

Now, how to create a new instance Ain allocated memory?

I tried this with:

*pObj = A();

But this did not work - the destructor received a call immediately after constructor A.

+3
source share
6 answers

You can use the new location:

A* pObj = new ( some_allocator_im_forced_to_use( sizeof( A ) ) ) A;

A , some_allocator_im_forced_to_use. void*, , A .

, , delete pObj .

pObj->~A();
// Call custom allocator corresponding deallocation function on (void*)pObj

, shared_ptr .

+8

:

new (pObj) A;

-, delete (), new:

pObj->~A();
some_deallocator_im_forced_to_use( pObj );
+3

" "

: " " ?

+2
+1

.

, , <new>, ::new ... .

- , . . , ; , .

#include <stddef.h>
#include <iostream>

void* some_allocator_im_forced_to_use( size_t size )
{
    std::cout << "Allocated " << size << " bytes." << std::endl;
    return ::operator new( size );
}

void some_deallocator_im_forced_to_use( void* p, size_t size )
{
    std::cout << "Deallocated " << size << " bytes." << std::endl;
    ::operator delete( p );
}

struct A
{
    int x_;
    A(): x_( 42 ) {}
    virtual ~A() {}
};

struct CustomAllocedA
    : A
{
    void* operator new( size_t size )
    {
        return some_allocator_im_forced_to_use( size );
    }

    void operator delete( void* p, size_t size )
    {
        some_deallocator_im_forced_to_use( p, size );
    }
};

int main()
{
    A* const    p    = new CustomAllocedA;

    std::cout << p->x_ << std::endl;
    delete p;
}

: "" , , , .

hth.,

+1

std::allocator, :

  • allocate
  • construct
  • destroy
  • deallocate

, , :

UB .

, , , , , , .

0
source

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


All Articles