<memory> 함수

addressof

개체의 실제 주소를 가져옵니다.

template <class T>
T* addressof(
    T& value) noexcept;    // before C++17

template <class T>
constexpr T* addressof(
    T& value) noexcept;    // C++17

template <class T>
const T* addressof(
    const T&& value) = delete;   // C++17

매개 변수

value
실제 주소를 가져올 개체 또는 함수입니다.

Return Value

오버로드된 value가 있는 경우에도, operator&()에서 참조하는 개체 또는 함수의 실제 주소입니다.

설명

align

지정된 맞춤 사양에 따라 정렬된 지정된 크기의 스토리지를 지정된 스토리지의 첫 번째 가능한 주소에 맞춥니다.

void* align(
    size_t alignment, // input
    size_t size,      // input
    void*& ptr,       // input/output
    size_t& space     // input/output
);

매개 변수

alignment
시도에 맞게 정렬됩니다.

size
정렬된 스토리지의 크기(바이트 단위)입니다.

ptr
사용 가능한 인접 스토리지 풀 중 사용할 스토리지 풀의 시작 주소입니다. 이 매개 변수는 출력 매개 변수이기도 하며 맞춤에 성공하면 새 시작 주소를 포함하도록 설정됩니다. 실패한 경우 align() 이 매개 변수는 수정되지 않습니다.

space
정렬된 스토리지를 만드는 데 사용하기 위해 align()에서 사용할 수 있는 총 공간입니다. 이 매개 변수는 출력 매개 변수이기도 하며, 정렬된 스토리지 및 관련된 모든 연결된 오버헤드를 차감한 후 스토리지 버퍼에 남아 있는 조정된 공간을 포함합니다.

실패한 경우 align() 이 매개 변수는 수정되지 않습니다.

Return Value

NULL 요청된 정렬된 버퍼가 사용 가능한 공간에 맞지 않는 경우 포인터입니다. 그렇지 않으면 새 값입니다ptr.

설명

수정된 ptrspace 매개 변수를 사용하면 align()alignment에 대해 다른 값을 사용하여 동일한 버퍼에서 size을 반복적으로 호출할 수 있습니다. 다음 코드 조각은 align()을 사용하는 방법을 보여 줍니다.

#include <type_traits> // std::alignment_of()
#include <memory>
//...
char buffer[256]; // for simplicity
size_t alignment = std::alignment_of<int>::value;
void * ptr = buffer;
std::size_t space = sizeof(buffer); // Be sure this results in the true size of your buffer

while (std::align(alignment, sizeof(MyObj), ptr, space)) {
    // You now have storage the size of MyObj, starting at ptr, aligned on
    // int boundary. Use it here if you like, or save off the starting address
    // contained in ptr for later use.
    // ...
    // Last, move starting pointer and decrease available space before
    // the while loop restarts.
    ptr = reinterpret_cast<char*>(ptr) + sizeof(MyObj);
    space -= sizeof(MyObj);
}
// At this point, align() has returned a null pointer, signaling it is not
// possible to allow more aligned storage in this buffer.

allocate_shared

지정된 할당자를 사용하여 지정된 형식에 대해 할당되고 생성되는 개체에 대한 shared_ptr을 만듭니다. shared_ptr를 반환합니다.

template <class T, class Allocator, class... Args>
shared_ptr<T> allocate_shared(
    Allocator alloc,
    Args&&... args);

매개 변수

alloc
개체를 만드는 데 사용된 할당자입니다.

args
개체가 되는 0개 이상의 인수입니다.

설명

이 함수는 alloc에 의해 할당되고 생성된 대로 T(args...)에 대한 포인터인 shared_ptr<T> 개체를 만듭니다.

atomic_compare_exchange_strong

template<class T>
bool atomic_compare_exchange_strong(
    shared_ptr<T>* u,
    shared_ptr<T>* v,
    shared_ptr<T> w);

atomic_compare_exchange_weak

template<class T>
bool atomic_compare_exchange_weak(
    shared_ptr<T>* u,
    shared_ptr<T>* v,
    shared_ptr<T> w);

atomic_compare_exchange_strong_explicit

template<class T>
bool atomic_compare_exchange_strong_explicit(
    shared_ptr<T>* u,
    shared_ptr<T>* v,
    shared_ptr<T> w,
    memory_order success,
    memory_order failure);

atomic_compare_exchange_weak_explicit

template<class T>
bool atomic_compare_exchange_weak_explicit(
    shared_ptr<T>* u,
    shared_ptr<T>* v,
    shared_ptr<T> w,
    memory_order success,
    memory_order failure);

atomic_exchange

template<class T>
shared_ptr<T> atomic_exchange(
    shared_ptr<T>* u,
    shared_ptr<T> r);

atomic_exchange_explicit

template<class T>
shared_ptr<T> atomic_exchange_explicit(
    shared_ptr<T>* u,
    shared_ptr<T> r,
    memory_order mo);

atomic_is_lock_free

template<class T>
bool atomic_is_lock_free(
    const shared_ptr<T>* u);

atomic_load

template<class T>
shared_ptr<T> atomic_load(
    const shared_ptr<T>* u);

atomic_load_explicit

template<class T>
shared_ptr<T> atomic_load_explicit(
    const shared_ptr<T>* u,
    memory_order mo);

atomic_store

template<class T>
void atomic_store(
    shared_ptr<T>* u,
    shared_ptr<T> r);

atomic_store_explicit

template<class T>
void atomic_store_explicit(
    shared_ptr<T>* u,
    shared_ptr<T> r,
    memory_order mo);

const_pointer_cast

shared_ptr로 const_cast를 수행합니다.

template <class T, class Other>
shared_ptr<T> const_pointer_cast(
    const shared_ptr<Other>& sp) noexcept;

template <class T, class Other>
shared_ptr<T> const_pointer_cast(
    shared_ptr<Other>&& sp) noexcept;

매개 변수

T
반환된 공유 포인터에 의해 제어되는 형식입니다.

Other
인수 공유 포인터에 의해 제어되는 형식입니다.

sp
인수 공유 포인터입니다.

설명

null 포인터를 반환하는 경우 const_cast<T*>(sp.get()) 템플릿 함수는 빈 shared_ptr 개체를 반환하고, 그렇지 않으면 소유sp하는 리소스를 소유하는 개체를 반환 shared_ptr<T> 합니다. const_cast<T*>(sp.get()) 식이 유효해야 합니다.

예시

// std__memory__const_pointer_cast.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

int main()
{
    std::shared_ptr<int> sp0(new int);
    std::shared_ptr<const int> sp1 =
        std::const_pointer_cast<const int>(sp0);

    *sp0 = 3;
    std::cout << "sp1 == " << *sp1 << std::endl;

    return (0);
}
sp1 == 3

declare_no_pointers

기본 주소 포인터와 블록 크기로 정의된 메모리 블록에 있는 문자에 추적 가능한 포인터가 포함될 수 없음을 가비지 수집기에 알립니다.

void declare_no_pointers(
    char* ptr,
    size_t size);

매개 변수

ptr
추적 가능한 포인터를 더 이상 포함하지 않는 첫 번째 문자의 주소입니다.

size
추적 가능한 포인터를 포함하지 않는, ptr에서 시작하는 블록의 크기입니다.

설명

이 함수는 범위 [ptr, ptr + size) 의 주소에 더 이상 추적 가능한 포인터가 포함되어 있지 않음을 가비지 수집기에게 알릴 수 있습니다. (할당된 스토리지에 대한 포인터는 연결할 수 없는 한 역참조해서는 안 됩니다.)

declare_reachable

지정된 주소가 할당된 스토리지에 대한 것이며 접근할 수 있음을 가비지 컬렉션에 알립니다.

void declare_reachable(
    void* ptr);

매개 변수

ptr
연결할 수 있는 할당된 유효한 스토리지 영역에 대한 포인터입니다.

설명

null이 아닌 경우 ptr 함수는 이제 연결할 수 있는 ptr 가비지 수집기, 즉 유효한 할당된 스토리지를 가리킵니다.

default_delete

operator new를 사용하여 할당된 개체를 삭제합니다. unique_ptr에 사용하는 데 적합합니다.

struct default_delete
{
    constexpr default_delete() noexcept = default;

    template <class Other, class = typename enable_if<is_convertible<Other*, T*>::value, void>::type>>
    default_delete(const default_delete<Other>&) noexcept;

    void operator()(T* ptr) const noexcept;
};

매개 변수

ptr
삭제할 개체에 대한 포인터입니다.

Other
삭제할 배열의 요소 형식입니다.

설명

클래스 템플릿은 클래스 템플릿에 사용하기unique_ptr에 적합한 할당된 operator new스칼라 개체를 삭제하는 삭제자를 설명합니다. 이 템플릿 클래스에는 명시적 특수화 default_delete<T[]>도 있습니다.

destroy_at

template <class T>
void destroy_at(
    T* location);

location->~T()와 동일합니다.

destroy

template <class ForwardIterator>
void destroy(
    ForwardIterator first,
    ForwardIterator last);

다음과 같습니다.

for (; first != last; ++first)
    destroy_at(addressof(*first));

destroy_n

template <class ForwardIterator, class Size>
ForwardIterator destroy_n(
    ForwardIterator first,
    Size count);

다음과 같습니다.

for (; count > 0; (void)++first, --count)
    destroy_at(addressof(*first));
return first;

dynamic_pointer_cast

shared_ptr로 dynamic_cast를 수행합니다.

template <class T, class Other>
shared_ptr<T> dynamic_pointer_cast(
    const shared_ptr<Other>& sp) noexcept;

template <class T, class Other>
shared_ptr<T> dynamic_pointer_cast(
    shared_ptr<Other>&& sp) noexcept;

매개 변수

T
반환된 공유 포인터에 의해 제어되는 형식입니다.

Other
인수 공유 포인터에 의해 제어되는 형식입니다.

sp
인수 공유 포인터입니다.

설명

null 포인터를 반환하는 경우 dynamic_cast<T*>(sp.get()) 템플릿 함수는 빈 shared_ptr 개체를 반환하고, 그렇지 않으면 소유sp하는 리소스를 소유하는 개체를 반환 shared_ptr<T> 합니다. dynamic_cast<T*>(sp.get()) 식이 유효해야 합니다.

예시

// std__memory__dynamic_pointer_cast.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

struct base
{
    virtual ~base() {}
    int value;
};

struct derived
    : public base
{
};

int main()
{
    std::shared_ptr<base> sp0(new derived);
    std::shared_ptr<derived> sp1 =
        std::dynamic_pointer_cast<derived>(sp0);

    sp0->value = 3;
    std::cout << "sp1->value == " << sp1->value << std::endl;

    return (0);
}
sp1->value == 3

get_deleter

에서 삭제자를 shared_ptr가져옵니다.

template <class Deleter, class T>
Deleter* get_deleter(
    const shared_ptr<T>& sp) noexcept;

매개 변수

Deleter
삭제자의 형식입니다.

T
공유 포인터에 의해 제어되는 형식입니다.

sp
공유 포인터입니다.

설명

템플릿 함수는 개체sp에 속하는 형식 Deleter 의 삭제자 포인터를 shared_ptr 반환합니다. deleter가 없거나 deleter 형식Deleter이 아닌 경우 sp 함수는 0을 반환합니다.

예시

// std__memory__get_deleter.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

struct base
{
    int value;
};

struct deleter
{
    void operator()(base *pb)
    {
        delete pb;
    }
};

int main()
{
    std::shared_ptr<base> sp0(new base);

    sp0->value = 3;
    std::cout << "get_deleter(sp0) != 0 == " << std::boolalpha
        << (std::get_deleter<deleter>(sp0) != 0) << std::endl;

    std::shared_ptr<base> sp1(new base, deleter());

    sp0->value = 3;
    std::cout << "get_deleter(sp1) != 0 == " << std::boolalpha
        << (std::get_deleter<deleter>(sp1) != 0) << std::endl;

    return (0);
}
get_deleter(sp0) != 0 == false
get_deleter(sp1) != 0 == true

get_pointer_safety

모든 가비지 수집기에서 간주된 포인터 안전 형식을 반환합니다.

pointer_safety get_pointer_safety() noexcept;

설명

이 함수는 자동 가비지 수집기가 가정하는 포인터 안전의 형식을 반환합니다.

get_temporary_buffer

지정된 요소 수를 초과하지 않는 요소 시퀀스에 임시 스토리지를 할당합니다.

template <class T>
pair<T *, ptrdiff_t> get_temporary_buffer(
    ptrdiff_t count);

매개 변수

count
메모리를 할당하도록 요청한 최대 요소 수입니다.

Return Value

첫 번째 구성 요소는 할당된 메모리에 대한 포인터이고, 두 번째 구성 요소는 저장할 수 있는 요소의 최대 수를 나타내는 버퍼의 크기를 제공하는 pair입니다.

설명

이 함수는 메모리에 대한 요청을 만들며 성공하지 못할 수 있습니다. 버퍼가 할당되지 않은 경우 함수는 두 번째 구성 요소는 0이고 첫 번째 구성 요소는 null 포인터인 쌍을 반환합니다.

임시 메모리에만 이 함수를 사용합니다.

예시

// memory_get_temp_buf.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

using namespace std;

int main( )
{
    // Create an array of ints
    int intArray [] = { 10, 20, 30, 40, 100, 200, 300, 1000, 2000 };
    int count = sizeof ( intArray ) / sizeof ( int );
    cout << "The number of integers in the array is: "
        << count << "." << endl;

    pair<int *, ptrdiff_t> resultPair;
    resultPair = get_temporary_buffer<int>( count );

    cout << "The number of elements that the allocated memory\n"
        << "could store is given by: resultPair.second = "
        << resultPair.second << "." << endl;
}
The number of integers in the array is: 9.
The number of elements that the allocated memory
could store is given by: resultPair.second = 9.

make_shared

기본 할당자를 사용하여 하나 이상의 인수에서 작성된 할당된 개체를 가리키는 shared_ptr를 만들고 반환합니다. 지정된 형식의 개체와 shared_ptr을 모두 할당 및 생성하여 개체의 공유 소유권을 관리하고 shared_ptr을 반환합니다.

template <class T, class... Args>
shared_ptr<T> make_shared(
    Args&&... args);

매개 변수

args
0개 이상의 생성자 인수입니다. 이 함수는 제공되는 인수에 따라 호출할 생성자 오버로드를 유추합니다.

설명

make_shared를 개체 및 shared_ptr을 만드는 간단하고 보다 효율적인 방법으로 사용하여 개체에 대한 공유 액세스를 동시에 관리할 수 있습니다. 의미상으로 다음 두 문은 동일합니다.

auto sp = std::shared_ptr<Example>(new Example(argument));
auto msp = std::make_shared<Example>(argument);

그러나 첫 번째 문은 두 개의 할당을 만들고, shared_ptr 개체의 할당이 성공한 후에 Example의 할당이 실패하면 명명되지 않은 Example 개체가 유출됩니다. make_shared를 사용하는 문은 관련된 함수 호출이 하나뿐이므로 더 간단합니다. 라이브러리가 개체와 스마트 포인터에 대해 단일 할당을 만들 수 있으므로 더 효율적입니다. 이 함수는 둘 다 더 빠르며 메모리 조각화가 줄어들며 한 할당에서는 예외가 발생하지 않지만 다른 할당에는 예외가 발생할 가능성이 없습니다. 개체를 참조하고 스마트 포인터의 참조 카운트를 업데이트하는 코드에 대한 집약성이 더 높아지므로 성능이 향상됩니다.

개체에 대한 공유 액세스가 필요하지 않은 경우 사용하는 make_unique 것이 좋습니다. 개체에 대한 사용자 지정 할당자를 지정해야 하는 경우 사용합니다 allocate_shared . 삭제자를 인수로 전달할 방법이 없으므로 개체에 사용자 지정 삭제자가 필요한 경우 사용할 make_shared 수 없습니다.

다음 예에서는 특정 생성자 오버로드를 호출하여 형식에 대한 공유 포인터를 만드는 방법을 보여 줍니다.

예시

// stl_make_shared.cpp
// Compile by using: cl /W4 /EHsc stl_make_shared.cpp
#include <iostream>
#include <string>
#include <memory>
#include <vector>

class Song {
public:
    std::wstring title_;
    std::wstring artist_;

    Song(std::wstring title, std::wstring artist) : title_(title), artist_(artist) {}
    Song(std::wstring title) : title_(title), artist_(L"Unknown") {}
};

void CreateSharedPointers()
{
    // Okay, but less efficient to have separate allocations for
    // Song object and shared_ptr control block.
    auto song = new Song(L"Ode to Joy", L"Beethoven");
    std::shared_ptr<Song> sp0(song);

    // Use make_shared function when possible. Memory for control block
    // and Song object are allocated in the same call:
    auto sp1 = std::make_shared<Song>(L"Yesterday", L"The Beatles");
    auto sp2 = std::make_shared<Song>(L"Blackbird", L"The Beatles");

    // make_shared infers which constructor to use based on the arguments.
    auto sp3 = std::make_shared<Song>(L"Greensleeves");

    // The playlist vector makes copies of the shared_ptr pointers.
    std::vector<std::shared_ptr<Song>> playlist;
    playlist.push_back(sp0);
    playlist.push_back(sp1);
    playlist.push_back(sp2);
    playlist.push_back(sp3);
    playlist.push_back(sp1);
    playlist.push_back(sp2);
    for (auto&& sp : playlist)
    {
        std::wcout << L"Playing " << sp->title_ <<
            L" by " << sp->artist_ << L", use count: " <<
            sp.use_count() << std::endl;
    }
}

int main()
{
    CreateSharedPointers();
}

이 예에서는 다음과 같은 출력을 생성합니다.

Playing Ode to Joy by Beethoven, use count: 2
Playing Yesterday by The Beatles, use count: 3
Playing Blackbird by The Beatles, use count: 3
Playing Greensleeves by Unknown, use count: 2
Playing Yesterday by The Beatles, use count: 3
Playing Blackbird by The Beatles, use count: 3

make_unique

지정된 인수를 unique_ptr 사용하여 생성되는 지정된 형식의 개체를 만들고 반환합니다.

// make_unique<T>
template <class T, class... Args>
unique_ptr<T> make_unique(Args&&... args);

// make_unique<T[]>
template <class T>
unique_ptr<T> make_unique(size_t size);

// make_unique<T[N]> disallowed
template <class T, class... Args>
/* unspecified */ make_unique(Args&&...) = delete;

매개 변수

T
unique_ptr이 가리키는 개체의 형식입니다.

Args
args로 지정된 생성자 인수의 형식입니다.

args
T 형식의 개체 생성자에 전달할 인수입니다.

elements
T 형식 요소의 배열입니다.

size
새 배열에 공간을 할당할 수 있는 요소의 수입니다.

설명

첫 번째 오버로드는 단일 개체에 사용됩니다. 배열에 대해 두 번째 오버로드가 호출됩니다. 세 번째 오버로드는 형식 인수()make_unique<T[N]>에 배열 크기를 지정하지 못하도록 합니다. 이 생성은 현재 표준에서 지원되지 않습니다. make_unique를 사용하여 배열에 대한 unique_ptr을 만드는 경우 배열 요소를 별도로 초기화해야 합니다. 이 오버로드 std::vector를 사용하는 대신 .

make_unique는 예외 안전성을 위해 신중하게 구현되기 때문에 make_unique 생성자를 직접 호출하는 대신 unique_ptr를 사용할 것을 추천합니다.

예시

다음 예제에서는 make_unique를 사용하는 방법을 보여 줍니다. 더 많은 예제는 방법: unique_ptr 인스턴스 만들기 및 사용을 참조하세요.

class Animal
{
private:
    std::wstring genus;
    std::wstring species;
    int age;
    double weight;
public:
    Animal(const wstring&, const wstring&, int, double){/*...*/ }
    Animal(){}
};

void MakeAnimals()
{
    // Use the Animal default constructor.
    unique_ptr<Animal> p1 = make_unique<Animal>();

    // Use the constructor that matches these arguments
    auto p2 = make_unique<Animal>(L"Felis", L"Catus", 12, 16.5);

    // Create a unique_ptr to an array of 5 Animals
    unique_ptr<Animal[]> p3 = make_unique<Animal[]>(5);

    // Initialize the elements
    p3[0] = Animal(L"Rattus", L"norvegicus", 3, 2.1);
    p3[1] = Animal(L"Corynorhinus", L"townsendii", 4, 1.08);

    // auto p4 = p2; //C2280

    vector<unique_ptr<Animal>> vec;
    // vec.push_back(p2); //C2280
    // vector<unique_ptr<Animal>> vec2 = vec; // C2280

    // OK. p2 no longer points to anything
    vec.push_back(std::move(p2)); 

    // unique_ptr overloads operator bool
    wcout << boolalpha << (p2 == false) << endl; // Prints "true"

    // OK but now you have two pointers to the same memory location
    Animal* pAnimal = p2.get();

    // OK. p2 no longer points to anything
    Animal* p5 = p2.release();
}

unique_ptr과 관련하여 오류 C2280이 표시되는 경우 대부분 삭제된 함수인 해당 복사 생성자를 호출하려고 했기 때문입니다.

owner_less

공유된 포인터와 약한 포인트에 대한 소유권 기반의 혼합된 비교를 허용합니다. 멤버 함수 owner_before에 의해 왼쪽 매개 변수가 오른쪽 매개 변수보다 먼저 순서 지정된 경우 true를 반환합니다.

template <class T>
    struct owner_less; // not defined

template <class T>
struct owner_less<shared_ptr<T>>
{
    bool operator()(
        const shared_ptr<T>& left,
        const shared_ptr<T>& right) const noexcept;

    bool operator()(
        const shared_ptr<T>& left,
        const weak_ptr<T>& right) const noexcept;

    bool operator()(
        const weak_ptr<T>& left,
        const shared_ptr<T>& right) const noexcept;
};

template <class T>
struct owner_less<weak_ptr<T>>
    bool operator()(
        const weak_ptr<T>& left,
        const weak_ptr<T>& right) const noexcept;

    bool operator()(
        const weak_ptr<T>& left,
        const shared_ptr<T>& right) const noexcept;

    bool operator()(
        const shared_ptr<T>& left,
        const weak_ptr<T>& right) const noexcept;
};

template<> struct owner_less<void>
{
    template<class T, class U>
    bool operator()(
        const shared_ptr<T>& left,
        const shared_ptr<U>& right) const noexcept;

    template<class T, class U>
    bool operator()(
        const shared_ptr<T>& left,
        const weak_ptr<U>& right) const noexcept;

    template<class T, class U>
    bool operator()(
        const weak_ptr<T>& left,
        const shared_ptr<U>& right) const noexcept;

    template<class T, class U>
    bool operator()(
        const weak_ptr<T>& left,
        const weak_ptr<U>& right) const noexcept;
};

매개 변수

left
공유 또는 약한 포인터입니다.

right
공유 또는 약한 포인터입니다.

설명

클래스 템플릿은 모든 멤버 연산자를 반환으로 정의합니다 left.owner_before(right).

reinterpret_pointer_cast

캐스트를 사용하여 기존 공유 포인터에서 새 shared_ptr 포인터를 만듭니다.

template<class T, class U>
shared_ptr<T> reinterpret_pointer_cast(
    const shared_ptr<U>& ptr) noexcept;

template<class T, class U>
shared_ptr<T> reinterpret_pointer_cast(
    shared_ptr<U>&& ptr) noexcept;

매개 변수

ptr
에 대한 참조입니다 shared_ptr<U>.

설명

비어 있으면 ptrshared_ptr 항목도 비어 있습니다. 그렇지 않으면 소유권을 ptr공유합니다. 새 공유 포인터는 평가 reinterpret_cast<Y*>(ptr.get())의 결과이며, 여기서는 다음과 Y 같이 typename std::shared_ptr<T>::element_type표시됩니다. 올바른 형식이 아닌 경우 reinterpret_cast<T*>((U*)nullptr) 동작이 정의되지 않습니다.

lvalue 참조를 사용하는 템플릿 함수는 C++17의 새로운 기능입니다. rvalue 참조를 사용하는 템플릿 함수는 C++20의 새로운 기능입니다.

return_temporary_buffer

get_temporary_buffer 템플릿 함수를 사용하여 할당된 임시 메모리를 취소합니다.

template <class T>
void return_temporary_buffer(
    T* buffer);

매개 변수

buffer
할당을 취소할 메모리에 대한 포인터입니다.

설명

임시 메모리에만 이 함수를 사용합니다.

예시

// memory_ret_temp_buf.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

using namespace std;

int main( )
{
    // Create an array of ints
    int intArray [] = { 10, 20, 30, 40, 100, 200, 300 };
    int count = sizeof ( intArray ) / sizeof ( int );
    cout << "The number of integers in the array is: "
         << count << "." << endl;

    pair<int *, ptrdiff_t> resultPair;
    resultPair = get_temporary_buffer<int>( count );

    cout << "The number of elements that the allocated memory\n"
         << " could store is given by: resultPair.second = "
         << resultPair.second << "." << endl;

    int* tempBuffer = resultPair.first;

    // Deallocates memory allocated with get_temporary_buffer
    return_temporary_buffer( tempBuffer );
}
The number of integers in the array is: 7.
The number of elements that the allocated memory
could store is given by: resultPair.second = 7.

static_pointer_cast

shared_ptr에 대한 정적 캐스팅입니다.

template <class T, class Other>
shared_ptr<T> static_pointer_cast(
    const shared_ptr<Other>& sp) noexcept;

template <class T, class Other>
shared_ptr<T> static_pointer_cast(
    shared_ptr<Other>&& sp) noexcept;

매개 변수

T
반환된 공유 포인터에 의해 제어되는 형식입니다.

Other
인수 공유 포인터에 의해 제어되는 형식입니다.

sp
인수 공유 포인터입니다.

설명

템플릿 함수는 빈 개체인 경우 spshared_ptrshared_ptr 개체를 반환하고, 그렇지 않으면 소유sp하는 리소스를 소유하는 개체를 반환 shared_ptr<T> 합니다. static_cast<T*>(sp.get()) 식이 유효해야 합니다.

예시

// std__memory__static_pointer_cast.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

struct base
{
    int value;
};

struct derived
    : public base
{
};

int main()
{
    std::shared_ptr<base> sp0(new derived);
    std::shared_ptr<derived> sp1 =
        std::static_pointer_cast<derived>(sp0);

    sp0->value = 3;
    std::cout << "sp1->value == " << sp1->value << std::endl;

    return (0);
}
sp1->value == 3

swap

두 개체 shared_ptr또는 unique_ptrweak_ptr 개체를 교환합니다.

template <class T>
void swap(
    shared_ptr<T>& left,
    shared_ptr<T>& right) noexcept;

template <class T, class Deleter>
void swap(
    unique_ptr<T, Deleter>& left,
    unique_ptr<T, Deleter>& right) noexcept;

template <class T>
void swap(
    weak_ptr<T>& left,
    weak_ptr<T>& right) noexcept;

매개 변수

T
인수 포인터에 의해 제어되는 형식입니다.

Deleter
고유 포인터 형식의 삭제자입니다.

left
왼쪽 포인터입니다.

right
오른쪽 포인터입니다.

설명

템플릿 함수는 left.swap(right)을 호출합니다.

예시

// std__memory__swap.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

int main()
{
    std::shared_ptr<int> sp1(new int(5));
    std::shared_ptr<int> sp2(new int(10));
    std::cout << "*sp1 == " << *sp1 << std::endl;

    sp1.swap(sp2);
    std::cout << "*sp1 == " << *sp1 << std::endl;

    swap(sp1, sp2);
    std::cout << "*sp1 == " << *sp1 << std::endl;
    std::cout << std::endl;

    std::weak_ptr<int> wp1(sp1);
    std::weak_ptr<int> wp2(sp2);
    std::cout << "*wp1 == " << *wp1.lock() << std::endl;

    wp1.swap(wp2);
    std::cout << "*wp1 == " << *wp1.lock() << std::endl;

    swap(wp1, wp2);
    std::cout << "*wp1 == " << *wp1.lock() << std::endl;

    return (0);
}
*sp1 == 5
*sp1 == 10
*sp1 == 5

*wp1 == 5
*wp1 == 10
*wp1 == 5

undeclare_no_pointers

기본 주소 포인터와 블록 크기로 정의된 메모리 블록에 있는 문자는 이제 추적이 가능한 포인터를 포함할 수 있음을 가비지 수집기에 알립니다.

void undeclare_no_pointers(
    char* ptr,
    size_t size);

매개 변수

ptr
를 사용하여 declare_no_pointers이전에 표시된 메모리 주소에 대한 포인터입니다.

size
메모리 범위의 바이트 수입니다. 이 값은 호출에 사용된 번호와 declare_no_pointers 같아야 합니다.

설명

이 함수는 주소 [ptr, ptr + size) 범위에 추적 가능한 포인터가 포함될 수 있음을 가비지 수집기에게 알릴 수 있습니다.

undeclare_reachable

지정된 메모리 위치에 대한 연결 가능성 선언을 취소합니다.

template <class T>
T *undeclare_reachable(
    T* ptr);

매개 변수

ptr
를 사용하여 declare_reachable이전에 표시된 메모리 주소에 대한 포인터입니다.

설명

그렇지 않은 nullptr경우 ptr 함수는 더 이상 연결할 수 없는 가비지 수집기를 ptr 알려줍니다. 같 ptr음과 비교되는 안전하게 파생된 포인터를 반환합니다.

uninitialized_copy

지정된 소스 범위에서 초기화되지 않은 대상 범위로 개체를 복사합니다.

template <class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(
    InputIterator first,
    InputIterator last,
    ForwardIterator dest);

template <class ExecutionPolicy, class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(
    ExecutionPolicy&& policy,
    InputIterator first,
    InputIterator last,
    ForwardIterator dest);

매개 변수

policy
사용할 실행 정책입니다.

first
소스 범위에 있는 첫 번째 요소를 주소 지정하는 입력 반복기입니다.

last
소스 범위에 있는 마지막 요소를 주소 지정하는 입력 반복기입니다.

dest
대상 범위에 있는 첫 번째 요소를 주소 지정하는 정방향 반복기입니다.

Return Value

원본 범위가 비어 있지 않은 한 대상 범위를 벗어난 첫 번째 위치의 주소를 지정하는 정방향 반복기입니다.

설명

이 알고리즘을 사용하면 개체 생성에서 메모리 할당을 분리할 수 있습니다.

템플릿 함수는 다음을 효과적으로 실행합니다.

while (first != last)
{
    new (static_cast<void*>(&* dest++))
        typename iterator_traits<InputIterator>::value_type(*first++);
}
return dest;

코드에서 예외를 throw하지 않는 경우 이 경우 생성된 모든 개체가 제거되고 예외가 다시 throw됩니다.

실행 정책을 사용하는 오버로드는 C++17의 새로운 기능입니다.

예시

// memory_uninit_copy.cpp
// compile with: /EHsc /W3
#include <memory>
#include <iostream>

using namespace std;

class Integer
{
public:
    Integer(int x) : value(x) {}
    int get() { return value; }
private:
    int value;
};

int main()
{
    int Array[] = { 10, 20, 30, 40 };
    const int N = sizeof(Array) / sizeof(int);

    cout << "The initialized Array contains " << N << " elements: ";
    for (int i = 0; i < N; i++)
    {
        cout << " " << Array[i];
    }
    cout << endl;

    Integer* ArrayPtr = (Integer*)malloc(N * sizeof(int));
    Integer* LArrayPtr = uninitialized_copy(
        Array, Array + N, ArrayPtr);  // C4996

    cout << "Address of position after the last element in the array is: "
        << &Array[0] + N << endl;
    cout << "The iterator returned by uninitialized_copy addresses: "
        << (void*)LArrayPtr << endl;
    cout << "The address just beyond the last copied element is: "
        << (void*)(ArrayPtr + N) << endl;

    if ((&Array[0] + N) == (void*)LArrayPtr)
        cout << "The return value is an iterator "
        << "pointing just beyond the original array." << endl;
    else
        cout << "The return value is an iterator "
        << "not pointing just beyond the original array." << endl;

    if ((void*)LArrayPtr == (void*)(ArrayPtr + N))
        cout << "The return value is an iterator "
        << "pointing just beyond the copied array." << endl;
    else
        cout << "The return value is an iterator "
        << "not pointing just beyond the copied array." << endl;

    free(ArrayPtr);

    cout << "Note that the exact addresses returned will vary\n"
        << "with the memory allocation in individual computers."
        << endl;
}

uninitialized_copy_n

입력 반복기에서 지정된 수의 요소의 복사본을 만듭니다. 복사본은 정방향 반복기에 배치됩니다.

template <class InputIterator, class Size, class ForwardIterator>
ForwardIterator uninitialized_copy_n(
    InputIterator first,
    Size count,
    ForwardIterator dest);

template <class ExecutionPolicy, class InputIterator, class Size, class ForwardIterator>
ForwardIterator uninitialized_copy_n(
    ExecutionPolicy&& policy,
    InputIterator first,
    Size count,
    ForwardIterator dest);

매개 변수

policy
사용할 실행 정책입니다.

first
복사할 개체를 참조하는 입력 반복기입니다.

count
개체를 반복할 횟수를 지정하는 부호 있는 또는 부호 없는 정수 형식입니다.

dest
새 복사본의 위치를 참조하는 정방향 반복기입니다.

Return Value

대상을 벗어나는 첫 번째 위치를 주소 지정하는 정방향 반복기입니다. 원본 범위가 비어 있으면 반복기가 주소를 지정합니다 first.

설명

템플릿 함수는 다음 코드를 효과적으로 실행합니다.

    for (; 0 < count; --count)
        new (static_cast<void*>(&* dest++))
            typename iterator_traits<InputIterator>::value_type(*first++);
    return dest;

코드에서 예외를 throw하지 않는 경우 이 경우 생성된 모든 개체가 제거되고 예외가 다시 throw됩니다.

실행 정책을 사용하는 오버로드는 C++17의 새로운 기능입니다.

uninitialized_default_construct

기본값은 지정된 범위에서 반복기의 개체를 생성합니다 value_type .

template <class ForwardIterator>
void uninitialized_default_construct(
    ForwardIterator first,
    ForwardIterator last);

template <class ExecutionPolicy, class ForwardIterator>
void uninitialized_default_construct(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    ForwardIterator last);

매개 변수

policy
사용할 실행 정책입니다.

first
생성할 범위의 첫 번째 요소에 주소를 지정하는 반복기입니다.

last
생성할 범위의 마지막 요소 중 하나 이상의 주소를 지정하는 반복기입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; first != last; ++first)
    ::new (static_cast<void*>(addressof(*first)))
        typename iterator_traits<ForwardIterator>::value_type;

예외가 throw되면 이전에 생성된 개체가 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uninitialized_default_construct_n

기본값은 지정된 위치에서 시작하여 반복기의 지정된 개수의 value_type개체를 생성합니다.

template <class ForwardIterator, class Size>
ForwardIterator uninitialized_default_construct_n(
    ForwardIterator first,
    Size count);

template <class ExecutionPolicy, class ForwardIterator, class Size>
ForwardIterator uninitialized_default_construct_n(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    Size count);

매개 변수

policy
사용할 실행 정책입니다.

first
생성할 대상 범위의 첫 번째 요소에 주소를 지정하는 반복기입니다.

count
생성할 대상 범위의 요소 수입니다.

Return Value

원본 범위가 비어 있지 않은 한 대상 범위를 벗어난 첫 번째 위치의 주소를 지정하는 정방향 반복기입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; count>0; (void)++first, --count)
    ::new (static_cast<void*>(addressof(*first)))
        typename iterator_traits<ForwardIterator>::value_type;
return first;

예외가 throw되면 이전에 생성된 개체가 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uninitialized_fill

지정된 값의 개체를 초기화되지 않은 대상 범위로 복사합니다.

template <class ForwardIterator, class T>
void uninitialized_fill(
    ForwardIterator first,
    ForwardIterator last,
    const T& value);

template <class ExecutionPolicy, class ForwardIterator, class T>
void uninitialized_fill(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    ForwardIterator last,
    const T& value);

매개 변수

policy
사용할 실행 정책입니다.

first
초기화할 대상 범위의 첫 번째 요소에 주소를 지정하는 정방향 반복기입니다.

last
초기화할 대상 범위의 마지막 요소에 주소를 지정하는 정방향 반복기입니다.

value
대상 범위를 초기화하는 데 사용할 값입니다.

설명

이 알고리즘을 사용하면 개체 생성에서 메모리 할당을 분리할 수 있습니다.

템플릿 함수는 다음을 효과적으로 실행합니다.

while (first != last)
    new (static_cast<void*>(&* first ++))
        typename iterator_traits<ForwardIterator>::value_type (value);

코드에서 예외를 throw하지 않는 경우 이 경우 생성된 모든 개체가 제거되고 예외가 다시 throw됩니다.

실행 정책을 사용하는 오버로드는 C++17의 새로운 기능입니다.

예시

// memory_uninit_fill.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

using namespace std;

class Integer
{
public:
    // No default constructor
    Integer( int x ) : value( x ) {}
    int get() { return value; }
private:
    int value;
};

int main()
{
    const int N = 10;
    Integer value ( 25 );
    Integer* Array = ( Integer* ) malloc( N * sizeof( int ) );
    uninitialized_fill( Array, Array + N, value );
    cout << "The initialized Array contains: ";
    for ( int i = 0; i < N; i++ )
        {
            cout << Array[ i ].get() << " ";
        }
    cout << endl;
}
The initialized Array contains: 25 25 25 25 25 25 25 25 25 25

uninitialized_fill_n

지정한 값의 개체를 초기화되지 않은 대상 범위의 지정된 요소 수에 복사합니다.

template <class ForwardIterator, class Size, class T>
ForwardIterator uninitialized_fill_n(
    ForwardIterator first,
    Size count,
    const T& value);

template <class ExecutionPolicy, class ForwardIterator, class Size, class T>
ForwardIterator uninitialized_fill_n(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    Size count,
    const T& value);

매개 변수

policy
사용할 실행 정책입니다.

first
초기화할 대상 범위의 첫 번째 요소에 주소를 지정하는 정방향 반복기입니다.

count
초기화할 요소의 수입니다.

value
대상 범위를 초기화하는 데 사용할 값입니다.

설명

이 알고리즘을 사용하면 개체 생성에서 메모리 할당을 분리할 수 있습니다.

템플릿 함수는 다음을 효과적으로 실행합니다.

while (0 < count--)
    new (static_cast<void*>(&* first++))
        typename iterator_traits<ForwardIterator>::value_type(value);
return first;

코드에서 예외를 throw하지 않는 경우 이 경우 생성된 모든 개체가 제거되고 예외가 다시 throw됩니다.

실행 정책을 사용하는 오버로드는 C++17의 새로운 기능입니다.

예시

// memory_uninit_fill_n.cpp
// compile with: /EHsc /W3
#include <memory>
#include <iostream>

using namespace std;

class Integer
{
public:
    // No default constructor
    Integer( int x ) : value( x ) {}
    int get() { return value; }
private:
    int value;
};

int main()
{
    const int N = 10;
    Integer value( 60 );
    Integer* Array = ( Integer* ) malloc( N * sizeof( int ) );
    uninitialized_fill_n( Array, N, value );  // C4996
    cout << "The uninitialized Array contains: ";
    for ( int i = 0; i < N; i++ )
        cout << Array[ i ].get() <<  " ";
}

uninitialized_move

원본 범위에서 초기화되지 않은 대상 메모리 영역으로 요소를 이동합니다.

template <class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_move(
    InputIterator first,
    InputIterator last,
    ForwardIterator dest);

template <class ExecutionPolicy, class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_move(
    ExecutionPolicy&& policy,
    InputIterator first,
    InputIterator last,
    ForwardIterator dest);

매개 변수

policy
사용할 실행 정책입니다.

first
이동할 원본 범위의 첫 번째 요소 주소를 지정하는 입력 반복기입니다.

last
이동할 원본 범위의 마지막 요소 중 하나를 주소 지정하는 입력 반복기입니다.

dest
대상 범위의 시작입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; first != last; (void)++dest, ++first)
    ::new (static_cast<void*>(addressof(*dest)))
        typename iterator_traits<ForwardIterator>::value_type(std::move(*first));
return dest;

예외가 throw되면 원본 범위의 일부 개체가 유효하지만 지정되지 않은 상태로 남을 수 있습니다. 이전에 생성된 개체는 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uninitialized_move_n

원본 범위에서 초기화되지 않은 대상 메모리 영역으로 지정된 개수의 요소를 이동합니다.

template <class InputIterator, class Size, class ForwardIterator>
pair<InputIterator, ForwardIterator> uninitialized_move_n(
    InputIterator first,
    Size count,
    ForwardIterator dest);

template <class ExecutionPolicy, class InputIterator, class Size, class ForwardIterator>
pair<InputIterator, ForwardIterator> uninitialized_move_n(
    ExecutionPolicy&& policy,
    InputIterator first,
    Size count,
    ForwardIterator dest);

매개 변수

policy
사용할 실행 정책입니다.

first
이동할 원본 범위의 첫 번째 요소 주소를 지정하는 입력 반복기입니다.

count
이동할 원본 범위의 요소 수입니다.

dest
대상 범위의 시작입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; count > 0; ++dest, (void) ++first, --count)
    ::new (static_cast<void*>(addressof(*dest)))
        typename iterator_traits<ForwardIterator>::value_type(std::move(*first));
return {first, dest};

예외가 throw되면 원본 범위의 일부 개체가 유효하지만 지정되지 않은 상태로 남을 수 있습니다. 이전에 생성된 개체는 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uninitialized_value_construct

지정된 범위에서 값 초기화에 따라 반복기의 value_type 개체를 생성합니다.

template <class ForwardIterator>
void uninitialized_value_construct(
    ForwardIterator first,
    ForwardIterator last);

template <class ExecutionPolicy, class ForwardIterator>
void uninitialized_value_construct(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    ForwardIterator last);

매개 변수

policy
사용할 실행 정책입니다.

first
값 구문에 대한 범위의 첫 번째 요소 주소를 지정하는 반복기입니다.

last
값 구문 범위의 마지막 요소를 지나서 주소를 지정하는 반복기입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; first != last; ++first)
    ::new (static_cast<void*>(addressof(*first)))
        typename iterator_traits<ForwardIterator>::value_type();

예외가 throw되면 이전에 생성된 개체가 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

메모리 할당 오류가 발생하면 예외가 std::bad_alloc throw됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uninitialized_value_construct_n

지정된 위치에서 시작하여 값 초기화별로 반복기의 지정된 개수의 value_type 개체를 생성합니다.

template <class ForwardIterator, class Size>
ForwardIterator uninitialized_value_construct_n(
    ForwardIterator first,
    Size count);

template <class ExecutionPolicy, class ForwardIterator, class Size>
ForwardIterator uninitialized_value_construct_n(
    ExecutionPolicy&& policy,
    ForwardIterator first,
    Size count);

매개 변수

policy
사용할 실행 정책입니다.

first
생성할 대상 범위의 첫 번째 요소에 주소를 지정하는 반복기입니다.

count
생성할 대상 범위의 요소 수입니다.

설명

실행 정책이 없는 버전은 사실상 다음과 같습니다.

for (; count > 0; (void)++first, --count)
    ::new (static_cast<void*>(addressof(*first)))
        typename iterator_traits<ForwardIterator>::value_type();
return first;

예외가 throw되면 이전에 생성된 개체가 지정되지 않은 순서로 제거됩니다.

실행 정책이 있는 버전은 결과가 동일하지만 지정된 policy버전에 따라 실행됩니다.

메모리 할당 오류가 발생하면 예외가 std::bad_alloc throw됩니다.

이러한 함수는 C++17의 새로운 기능입니다.

uses_allocator_v

템플릿의 값에 액세스하기 위한 도우미 변수 템플릿입니다 uses_allocator .

template <class T, class Alloc>
inline constexpr bool uses_allocator_v = uses_allocator<T, Alloc>::value;

참고 항목

<memory>