Incomputable
Incomputable

Reputation: 2208

How to disallow temporaries in functions taking const references?

Background:

Lets say I have something like this:

struct item
{
    int x;
    item(int y): x(y) {}
}

class item_view
{
    const item& it;
public:
    item_view(const item& it_) : it(it_) {}

    friend std::ostream& operator<<(std::ostream& os, const item_view& view)
    {return os;} //actually is more complicated
}

The reason why I cannot just overload operator<< is that it is more human friendly, and view is used to pass the data to SQL, so ticks and some other characters must be escaped.

Problem:

Somebody might want to do something like this:

auto view = item_view(2);
std::cout << view;

This seems to be undefined behavior.

Question:

How can I prevent construction of item_view from temporaries?

Upvotes: 7

Views: 361

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

You can provide an additional overload that's a better matches for temporaries and then delete it. For example :

#include <string>

void foo(const std::string &) {}
void foo(std::string &&) = delete;

int main()
{
    std::string world = "World";
    foo("Hello");   // Doesn't compile, wants to use foo(std::string &&)
    foo(world);     // Compiles
}

Upvotes: 8

Related Questions