How can you return something containing unique_ptr?

Hi.

I've been trying out the "new" (new to me, even though it's now 4 years old) C++11 stuff, specifically the unique_ptr, and was wondering: how do you return, by value, an object containing a unique_ptr data member?
std::unique_ptr<> is MoveConstructible and MoveAssignable.

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
29
30
31
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <type_traits>

struct A
{
    A( const char* cstr ) : ptr( std::make_unique<std::string>(cstr) ) {}
    
    // all these are moveable types
    std::vector<int> vec { 0, 1, 2, 3, 4 } ;
    std::string str = "abcd" ;
    std::unique_ptr<std::string> ptr ;
};

A foo() { return "hello world!" ; }

int main()
{
    std::cout << std::boolalpha << std::is_move_constructible<A>::value << '\n' // true
              << std::is_move_assignable<A>::value << '\n' // true
              << std::is_copy_constructible<A>::value << '\n' // false
              << std::is_copy_assignable<A>::value << '\n' ; // false

    A a = foo() ;
    std::cout << *(a.ptr) << '\n' ; // hello world!

    A a2( std::move(a) ) ;
    std::cout << *(a2.ptr) << '\n' ; // hello world!
}

http://coliru.stacked-crooked.com/a/55dd1688b41fcd83
I use it in void by using reference the & which you would include with the pointer. Something like this.

1
2
3
4
5
6
7
8
9
10
11
12
void insertFirst(nodeType *& head, string item)
{
    // step 1. Make the "New node"
    nodeType *newNode = new nodeType;
    newNode->info = item; // set the "info" on the newNode to the "item" received via function paramter
    
    // step 2. Set the "Link" of "new node" to the current "head"
    newNode->link = head;
    
    // step 3. Update "head" to now point to this "new node"
    head = newNode;
}
Last edited on
Topic archived. No new replies allowed.