'Stack allocating intermediate objects in contructors

When a constructor allocates intermediate objects that need to be passed to other constructors with longer lifetimes, can the intermediate objects be stack-allocated?

For example, I have a class Reader that has various utilities build atop an std::wistream that has several constructors for various use cases:

  • Reader(std::unique_ptr<std::istream> bytestream)
  • Reader(char buffer[], size_t count)
  • Reader(const std::string str&)

The only relevant member data that Reader has is:

std::unique_ptr<std::wistream> m_character_stream

Note: wistream, not istream. The constructors construct the wistream in various ways depending on their argument types.

For example, the first constructor form, looks like this:

Reader::Reader(std::unique_ptr<std::istream> bytestream) {
    auto conversion = std::wbuffer_convert<std::codecvt_utf8<wchar_t>, wchar_t, std::char_traits<wchar_t>>(bytestream->rdbuf());

    m_character_stream = std::make_unique<std::wistream>(&conversion);
}

My questions are:

  1. I guess since I'm being passed a unique_ptr, that I have no choice but to std::move it to some otherwise useless member variable to keep it alive until we're destructed? Even though the rest of my class will never use that variable directly, but only indirectly through m_character_stream?

  2. The conversion object is stack-allocated. Is that going to be a problem? I assume that when the constructor returns, that this object will be deleted. Will that cause std::wistream to malfunction? Does that mean I have to store conversion as otherwise useless member data to keep it alive as well? If so, is there a common pattern or naming convention for useless member data that exist only to keep things alive?

Since I have multiple constructors, I'd rather not have a bunch of constructor-specific member data attached to my class since that data won't be initialized most of the time. This just all smells wrong, but this is my first C++ project, so move semantics, ownership semantics, smart pointers, RAII, and all that crazy stuff is all pretty new to me and I'm trying to wrap my brain around it all.

I come from a Java/Python/Go background.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source