Scott Nelson
Scott Nelson

Reputation: 616

Getting c++11 auto initialization syntax right

I am newbie programmer in C++ (but a veteran programmer in other languages) and I am trying to use "Modern C++" in my code.

I am wondering what I am doing wrong here, trying to initialize an istream from a boost::asio::streambuf:

#include <iostream>
#include <boost/asio/streambuf.hpp>

class A {
  public:
    void foo();
  private:
    boost::asio::streambuf cmdStreamBuf_{};
};

void A::foo() {
  std::istream is1{&cmdStreamBuf_}; // works
  auto is2 = std::istream{&cmdStreamBuf_}; // does not compile
}

I get this error:

try.cpp:13:41: error: use of deleted function 'std::basic_istream<char>::basic_istream(const std::basic_istream<char>&)'

I am not trying to copy; I thought I was constructing an std::istream!

Upvotes: 2

Views: 106

Answers (1)

Scott Nelson
Scott Nelson

Reputation: 616

Since all the answers were in the comments, I thought I'd finish this off by doing an official answer myself.

I am using a c++ library that doesn't have movable streams, and this matters because

auto is2 = std::istream{&cmdStreamBuf_};

creates a new std::istream and then initializes is2 with that rvalue (temporary object). It initializes it by calling the copy constructor or the move constructor. My c++ library apparently does not have either of these constructors, therefore the call fails.

I had originally thought that

auto varname = typename{...};

was the conceptually the same as

typename varname{...};

but it is not. So, this is an instance where you can't use auto to create a variable.

(sigh) And I was really hyped on using auto everywhere.

Upvotes: 2

Related Questions