Namespaces
Variants
Views
Actions

std::unique_ptr::operator[]

From cppreference.com
< cpp‎ | memory‎ | unique ptr
Revision as of 15:12, 2 November 2012 by P12bot (Talk | contribs)

 
 
 
 
 

Template:ddcl list begin <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
T& operator[](size_t i) const;
</td>

<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end

operator[] provides access to elements of an array managed by a unique_ptr.

The parameter i is required to be a valid array index.

Contents

Parameters

i - the index of the element to be returned

Return value

Returns the element at index i, i.e. get()[i].

Example

#include <iostream>
#include <memory>
 
int main() 
{
    const int size = 10; 
    std::unique_ptr<int[]> fact(new int[size]);
 
    for (int i = 0; i < size; ++i) {
        fact[i] = (i == 0) ? 1 : i * fact[i-1];
    }
 
    for (int i = 0; i < size; ++i) {
        std::cout << i << ": " << fact[i] << '\n';
    }
}

Output:

0: 1
1: 1
2: 2
3: 6
4: 24
5: 120
6: 720
7: 5040
8: 40320
9: 362880

See also

Template:cpp/memory/unique ptr/dcl list get