Heap allocation and uniqueness unique_ptr

Raw pointers can point to objects allocated on the stack or on the heap.

Heap placement example:

// heap allocation
int* rawPtr = new int(100);
std::cout << *rawPtr << std::endl;      // 100

Stack distribution example:

int i = 100;
int* rawPtr = &i;
std::cout << *rawPtr << std::endl;      // 100

Heap allocation using the auto_ptr example:

int* rawPtr = new int(100);
std::unique_ptr<int> uPtr(rawPtr);
std::cout << *uPtr << std::endl;        // 100

Stack distribution using the auto_ptr example:

int i = 100;
int* rawPtr = &i;
std::unique_ptr<int> uPtr(rawPtr);      // runtime error

Are smart pointers used to point to dynamically created objects on the heap? For C ++ 11, should we continue to use raw pointers to point to allocated stack objects? Thank.

+4
source share
4 answers

, new delete. , , .

, , , " delete". , unique_ptr delete , . , . , delete rawPtr;

, . std::unique_ptr<int> uPtr = make_unique<int>(100); . make_shared .

. , , , , delete. , , , . , , , , , ? , . , .

{
    char buf[32];
    auto erase_buf = [](char *p) { memset(p, 0, sizeof(buf)); };
    std::unique_ptr<char, decltype(erase_buf)> passwd(buf, erase_buf);

    get_password(passwd.get());
    check_password(passwd.get());
}
// The deleter will get called since passwd has gone out of scope.
// This will erase the memory in buf so that the password doesn't live
// on the stack any longer than it needs to.  This also works for
// exceptions!  Placing memset() at the end wouldn't catch that.
+3

, delete , new.

( "" ), " " ' , .

" " ? ++ 11 ?

, , , .

  • (), . , .
  • (), - , .

, ( int):

auto uPtr = std::make_unique<int>(100);

uPtr , . int () delete ed .

new delete . make_unique make_shared, new .

+3

" " ?

, , .

++ ( ). , .

+2

" " ?

, . , std::unique_ptr ( (3)/(4) ), , -, "deleter", . ( ).

++ 11 ? .

, "" , - ; , , .

Another place to use is when you implement a class that has a complex ownership template for protected / private members.

PS: Please forget aboutstd::auto_ptr ... pretending it never existed :-)

+1
source

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


All Articles