std::unique_ptr<X> not work after transition the ownership

I have a std::unique<X> which work nicely. but after I am using std::move or returned through the function, the new std::unique<X> not work.

Here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "Widget.h"
#include <iostream>
#include <thread>
#include <memory>

#include <redisclient\redissyncclient.h>
std::unique_ptr<RedisSyncClient> createConnection()
{
    boost::asio::io_service io_service;
    std::unique_ptr<RedisSyncClient> client = std::make_unique<RedisSyncClient>(io_service);
    std::string errmsg;
    client->connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6379), errmsg);
    client->command("set", "zhu", "leo");
    return client;
}
int main()
{
    std::unique_ptr<RedisSyncClient> client = createConnection();
    client->command("set", "zhu", "jiawei");
    std::cin.get();
    return 0;
}


line13 the command is ok, but line19 the command crash the application.

Can anyone help figure out why? Thank u in advance.
Last edited on
Looks like you're creating a local object on the stack, that will be destroyed at the end of the function, and then trying to make a unique pointer to it. But you know that the destructor on the local object will be called at the end of the function, so unless the constructor function being called by std::make_unique<RedisSyncClient>(io_service); does make a complete copy of the local object, it's going to be a unique pointer to something that is going to be destroyed at the end of the function.

Try deleting line 9 and changing line 10 to something like this:

std::unique_ptr<RedisSyncClient> client (new boost::asio::io_service);
Last edited on
Oh, you're right. Thank u for helping me, Repeater.
Topic archived. No new replies allowed.