logo
down
shadow

shared_from_this causing bad_weak_ptr


shared_from_this causing bad_weak_ptr

By : user2950952
Date : November 17 2020, 11:58 AM
I wish did fix the issue. I am trying to keep a list of connected clients in asio. I have adapted the chat server example from the docs (http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/example/cpp03/chat/chat_server.cpp) and here's the important part of what I ended up with: , John Zwinck's essential analysis is spot on:
code :
void start_accept()
{
    tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);
    acceptor_.async_accept(new_connection->socket(),
            boost::bind(
                &tcp_server::handle_accept,
                this, new_connection, asio::placeholders::error
            )
        );
}

void handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)
{
    if (!error)
    {
        client->start();
        start_accept();
    }
}
#include <iostream>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

namespace asio = boost::asio;
using asio::ip::tcp;

class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
    typedef boost::shared_ptr<tcp_connection> sptr;

    tcp_connection(asio::io_service& io_service) : socket_(io_service), timer_(io_service)
    {
    }

    void start()
    {
        std::cout << "Created tcp_connection session\n";

        // post some work bound to this object; if you don't, the client gets
        // 'garbage collected' as the ref count goes to zero
        do_hello();
    }

    ~tcp_connection() {
        std::cout << "Destroyed tcp_connection\n";
    }

    tcp::socket& socket()
    {
        return socket_;
    }

  private:
    tcp::socket socket_;
    asio::deadline_timer timer_;

    void do_hello(boost::system::error_code const& ec = {}) {
        if (!ec) {
            asio::async_write(socket_, asio::buffer("Hello world\n"),
                    boost::bind(&tcp_connection::handle_written, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred)
                );
        }
    }

    void handle_written(boost::system::error_code const& ec, size_t /*bytes_transferred*/) {
        if (!ec) {
            timer_.expires_from_now(boost::posix_time::seconds(1));
            timer_.async_wait(boost::bind(&tcp_connection::do_hello, shared_from_this(), asio::placeholders::error));
        }
    }
};

class tcp_server
{
public:
    tcp_server(asio::io_service& io_service)
        : io_service_(io_service),
          acceptor_(io_service, tcp::endpoint(tcp::v4(), 6767))
    {
        start_accept();
    }

private:
    void start_accept()
    {
        tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);
        acceptor_.async_accept(new_connection->socket(),
                boost::bind(
                    &tcp_server::handle_accept,
                    this, new_connection, asio::placeholders::error
                )
            );
    }

    void handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)
    {
        if (!error)
        {
            client->start();
            start_accept();
        }
    }

    asio::io_service& io_service_;
    tcp::acceptor acceptor_;
};

int main()
{
    try
    {
        asio::io_service io_service;
        tcp_server server(io_service);

        boost::thread(boost::bind(&asio::io_service::run, &io_service)).detach();

        boost::this_thread::sleep_for(boost::chrono::seconds(4));
        io_service.stop();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }
}
sehe@desktop:/tmp$ time (./test& (for a in {1..4}; do nc 127.0.0.1 6767& done | nl&); sleep 2; killall nc; wait)
Created tcp_connection session
Created tcp_connection session
     1  Hello world
Created tcp_connection session
     2  Hello world
Created tcp_connection session
     3  Hello world
     4  Hello world
     5  Hello world
     6  Hello world
     7  Hello world
     8  Hello world
     9  Hello world
    10  Hello world
    11  Hello world
    12  Hello world
    13  
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection
Destroyed tcp_connection

real    0m4.003s
user    0m0.000s
sys 0m0.015s


Share : facebook icon twitter icon
exception: bad_weak_ptr while shared_from_this

exception: bad_weak_ptr while shared_from_this


By : mihai234
Date : March 29 2020, 07:55 AM
hop of those help? In order for enable_shared_from_this to work, you need to store pointer to this in std::shared_ptr prior to calling shared_from_this().
code :
class painter_t : public i_painter_t, public std::enable_shared_from_this<painter_t>
{
public:
    static std::shared_ptr<painter_t> create() { return std::make_shared<painter_t>(); }
}
std::bad_weak_ptr while shared_from_this

std::bad_weak_ptr while shared_from_this


By : Markus Hermann
Date : March 29 2020, 07:55 AM
std::bad_weak_ptr exception when using shared_from_this

std::bad_weak_ptr exception when using shared_from_this


By : Kelvin
Date : March 29 2020, 07:55 AM
it should still fix some issue You can't use shared_from_this in constructor since no shared_ptr is assigned yet. See this Why shared_from_this can't be used in constructor from technical standpoint?
However when the object is constructed and there is any shared_ptr associated with the instance, you are able to call shared_from_this as usual.
shared_from_this() causes std::bad_weak_ptr even when correctly using make_shared

shared_from_this() causes std::bad_weak_ptr even when correctly using make_shared


By : edprog
Date : March 29 2020, 07:55 AM
it should still fix some issue I think your problem might be that you use default private inheritance.
here is a simple example of a program that crashes:
code :
class GoodUsage : public std::enable_shared_from_this<GoodUsage>
{
public:
    void DoSomething()
    {
        auto good = shared_from_this();
    }
};

class BadUsage : std::enable_shared_from_this<BadUsage> // private inheritence
{
public:
    void DoSomething()
    {
        auto bad = shared_from_this();
    }
};


int main()
{
    auto good = std::make_shared<GoodUsage>();
    auto bad = std::make_shared<BadUsage>();
    good->DoSomething(); // ok
    bad->DoSomething(); // throws std::bad_weak_ptr    
}
std::bad_weak_ptr exception in shared_from_this after object construction

std::bad_weak_ptr exception in shared_from_this after object construction


By : Sheeba Siddiqui
Date : March 29 2020, 07:55 AM
Related Posts Related Posts :
  • C++ Error: C4430 and C2143 Error at an impossible place
  • How can I track object lifetime in C++11 lambda?
  • #include statement mapping in Biicode (biicode.conf)
  • std::equal gives "Term doesnt evaluate to a function taking 2 arguments"
  • C++ template argument as reference lvalue
  • Legal to forward declare C standard library entities but not C++ standard library entities?
  • Conversion of wchar_t* to string
  • VirtualTreeView - Embarcadero C++ Builder XE7 - 64 bits
  • I don't understand C++ pointer arithmetic
  • Invalid addition of constness? Error: Cannot use char** to initialize const char**
  • Initilize constructor of class from another class
  • what happens when a class object is used as an index for an array?
  • Read and straighten multiple images from vector string, get error: "vector subscript out of range" [c++]
  • Meaning of a few lines in C++
  • Map, pair-vector or two vectors...?
  • Redefinition error in ostream overload in template and inherited classes
  • CUDA 6.5: error MSB3191 Unable to create directory and LNK2001 Unresolved External symbol
  • Is it possible to overlap batched FFTs with CUDA's cuFFT library and cufftPlanMany?
  • How to delete function from DLL binary
  • How do I loop over a boost MPL list of non-default constructed classes?
  • Download page using IE engine + use POST
  • How to insert an element into ublas matrix with dynamic size
  • Using typedefs appropriately to avoid "typedef contamination"
  • C++ Simple Converting from Binary to Decimal
  • error deleting item from list after passing through function
  • C++: RVO, NRVO and returning local objects
  • performance map c++ find (g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3))
  • How to change the fundamental underlying container type for the adaptor containers?
  • Crash when SAFE_RELEASE is called on IMMDeviceEnumerator
  • Visual Studio C++, how to change the text color for "nullptr"
  • C++ , return string from function; boost::asio read / write
  • C++ and finance, trouble understanding syntax in these files
  • Exception Handling in underflow while doing POP in Stack
  • C++, Mongoose: How to make a POST request?
  • boost split method results in iterator error
  • Why Would Different Pointers Act As If They Shared The Same Values?
  • g++ dumped assembly output doesn't work
  • C++ Rotation matrix issue when used on a square
  • Avoiding multiple objects of same name in C++
  • Is it possible to get Lexer output from gcc or clang?
  • C++ getline pass file or cin
  • Find critical edges of an MST: possible with modified Prim's algorithm?
  • Converting wostringstream to wchar_t* Garbles Values
  • Causing segfault in program doesn't get caught by signal handler
  • Undefined symbol: _ZN7QString13toUtf8_helperERKS_ at runtime
  • proper usage of C dummy functions replacement in different environment
  • How do you save images of detected objects in OpenCV?
  • See if length between two equal numbers in deque is even
  • Random real in [0..1[ using Mersenne Twister
  • Writing the contents of a map through operator overloading
  • Defined operator works in main() but doesn't work in class
  • Can a throw or delete expression ever be dependent?
  • C++ finding the (largest) index of the largest element in an array
  • Can sizeof nested twice ever be a dependent expression?
  • Creation of objects from a string (C++)
  • OpenCV: extractor->descriptorSize() - Segfault
  • C++ generic iterator
  • Why HANDLE created by 'CreateEvent' isn't valid in another process?
  • Assistance with a Memory Allocation Error in c++, linux using g++
  • Returning by reference a member of a destroyed local variable
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org