passing a shared_ptr to this to an object owning a reference

0

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)

c++
reference
shared-ptr
circular-dependency
asked on Stack Overflow Mar 14, 2020 by TonyRomero

1 Answer

0

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);
answered on Stack Overflow Mar 14, 2020 by S.M. • edited Mar 14, 2020 by S.M.

User contributions licensed under CC BY-SA 3.0