简体   繁体   中英

passing a shared_ptr to this to an object owning a reference

The SharedEditor class owns a reference to an object of the NetworkServer class whereas the NetworkServer objects owns a std::vector<std::shared_ptr<SharedEditor>> of editors . In the SharedEditor constructor, the server.connect() method is called to save the its reference, in the server.connect() instead a shared pointer to that editor is saved into the server . The program compile and execute but it badly terminate.

NetworkServer.h

#include <queue>
#include <memory>
#include "SharedEditor.h"
#include "Message.h"

class NetworkServer {
private:
    std::vector<std::shared_ptr<SharedEditor>> editors;
    std::deque<Message> messages;

public:
    int connect(std::shared_ptr<SharedEditor> sharedEditor);
};

NetworkServer.cpp

#include <algorithm>
#include "NetworkServer.h"

static int id = 0;

int NetworkServer::connect(std::shared_ptr<SharedEditor> sharedEditor) {
    editors.push_back(sharedEditor);
    return id++;
}

SharedEditor.h

#include <vector>
#include <map>
#include "Symbol.h"

class NetworkServer;

class SharedEditor {
private:
    NetworkServer& _server;

public:

    SharedEditor(NetworkServer &server);

};

SharedEditor.cpp

#include <exception>
#include <algorithm>
#include <random>
#include <iostream>
#include "SharedEditor.h"
#include "NetworkServer.h"

SharedEditor::SharedEditor(NetworkServer &server)
        : _server(server), _counter(0), base(32), boundary(10) {
    _siteId = server.connect(std::shared_ptr<SharedEditor>(this));
}

main.cpp

#include <iostream>
#include "NetworkServer.h"

int main() {
    NetworkServer network;
    SharedEditor ed1(network);
    SharedEditor ed2(network);


    return 0;
}

It returns with -1073740940 (0xC0000374)

You misunderstood how smart pointers work.

server.connect(std::shared_ptr<SharedEditor>(this))

You pass the pointer this to the object allocated on the stack. You must pass only pointers to dynamically allocated objects on the memory heap.

You should do something like below, but your classes are poorly designed, since it is not clear from the semantics that network will own newly allocated object.

SharedEditor* ed1 = new SharedEditor(network);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM