user589321
user589321

Reputation: 109

Why does string_stream.str() = a_string; compile?

I can create an std::istringstream like so

std::istringstream string_stream(inp_string);

I can then change the contents of the stream:

string_stream.str(std::move(inp_string_2));

However, I might accidentally try something like this:

string_stream.str() = inp_string_2;

This compiles, but will not change the contents of string_stream. If you check the return value of std::istringstream::str() here, you will see that the return value is of non-reference type.

I believe that std::istringstream::str() is an r-value, and writing it on the left side of the equals sign should give an error, but the following code compiles in MSVC:

#include <iostream>
#include <string>
#include <sstream>


int main() {
    // Create string stream
    std::string inp_string = "this is a test string";
    std::istringstream string_stream(inp_string);


    // Try to replace the string stream
    std::string inp_string_2 = "a new test string";

    // incorrect:
    string_stream.str() = inp_string_2;            // Expected Error
    string_stream.str() = std::move(inp_string_2); // Expected Error

    // correct:
    // string_stream.str(std::move(inp_string_2));


    // Check contents of string stream
    std::cout << string_stream.str();
}

The output is

this is a test string

A Related Example

Below is similar example that will fail to compile:

#include <iostream>
#include <vector>


class MyClass {
private:
    std::vector<int> my_vec;

public:
    MyClass(std::vector<int>& vec) : my_vec(std::move(vec)){}

    int operator() (int i) {
        return my_vec[i];
    }
};


int main() {
    std::vector<int> inp = { 1, 2, 3, 4,  5 };
    MyClass my_class(inp);
    my_class(3) = 2;               // ERROR
    std::cout << my_class[3];

}

This gives the error

error C2106: '=': left operand must be l-value

as expected.

Upvotes: 3

Views: 63

Answers (0)

Related Questions