Set value of unique_ptr

Okay so say I have this.

1
2
3
std::unique_ptr<int> Blocks[10];

Blocks[0] = std::unique_ptr<int> (new int)


then I would like to do something equivalent to this

 
*Blocks[0] = 12;
Last edited on
12 as in memory address or value ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <memory>

int main(){


    std::unique_ptr<int> Blocks[10];


    // for assigning value
    Blocks[0] = std::unique_ptr<int>( new int( 12 ) );
    // for assigning to address
    Blocks[1] = std::unique_ptr<int>( (int*)12 );

    return 0;
}


you need to cast them to unique_ptr before assigning it
Last edited on
1
2
// Blocks[0] = 12;
Blocks[0] = std::unique_ptr<int>( new int(12) ) ;


In general:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <memory>
#include <array>

int main()
{
    struct block { ~block() { std::cout << "destructor: " << this << '\n' ; } };

    std::array< std::unique_ptr<block>, 5 > blocks ;

    const auto& print = [&blocks]
    {   for( auto& p : blocks ) std::cout << p.get() << ' ' ;
        std::cout << "\n\n" ;
    };

    print() ;

    blocks[1] = std::unique_ptr<block>( new block ) ;
    blocks[2] = std::unique_ptr<block>( new block ) ;
    blocks[4] = std::unique_ptr<block>( new block ) ;
    print() ;

    blocks[2] = 0 ; // calls deleter on blocks[2]
    print() ;

    blocks = {0} ; // calls deleter on all non-null pointers
    print() ;
}

http://coliru.stacked-crooked.com/a/c76e86874584f451
Okay fixed my own problem, I thought it wasn't working cause when I went:

 
std::cout << Blocks[0];


it equalled 1.

but then I went

 
std::cout << *Blocks[];


it equalled 12, just wasn't thinking

EDIT: oops I wrote this before I refreshed the page and saw your replies, Thanks anyway though :)
Last edited on
1
2
> // for assigning to address
> Blocks[1] = std::unique_ptr<int>( (int*)12 );


And what would happen when the std::unique_ptr<int> in Blocks[1] is destroyed (or reset)?
SEGFAULT ?
The program crashes ???
I don't know I never try ...

I guess that mustn't be done...
Topic archived. No new replies allowed.