c++boostboost-asio

Will moving ssl::context cause UB?


I have some code that creates an ssl::stream. The ssl::stream object takes an ssl::context in its constructor by reference. Creating an ssl::stream looks like this

ssl::context ssl_context(boost::asio::ssl::context::tls_client);
ssl_context.set_options(boost::asio::ssl::context::default_workarounds);
ssl::stream<stream_t> ssl_stream(std::move(socket), ssl_context);

Later I want to transfer ownership of the ssl_context and ssl_stream objects to another object like this:

session_t sess(std::move(ssl_stream), std::move(ssl_context));

Will further use of ssl::stream lead to UB? I ask because ssl::stream takes ssl::context by reference and we move the ssl::context object, the reference to which was passed to ssl::stream.

I think that after ssl::context was moved, ssl::stream has a dangling reference to it and uses this dangling reference to access SSL context. But I'm not sure.


Solution

  • No that will not cause UB.

    The documentation of the ssl::stream constructor does not state that the context reference needs to stay valid. Also, the ssl::stream does not store a reference to the ssl::context object:

      /// Construct a stream.
      /**
       * This constructor creates a stream and initialises the underlying stream
       * object.
       *
       * @param arg The argument to be passed to initialise the underlying stream.
       *
       * @param ctx The SSL context to be used for the stream.
       */
      template <typename Arg>
      stream(Arg&& arg, context& ctx)
        : next_layer_(static_cast<Arg&&>(arg)),
          core_(ctx.native_handle(), next_layer_.lowest_layer().get_executor())
      {
      }
    

    And context is designed as a movable type, so you're good, as long as the context stays alive (in any location).