Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
Incomputable Avatar asked Nov 08 '17 17:11

Incomputable


1 Answers

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
}
like image 139
François Andrieux Avatar answered Nov 03 '22 13:11

François Andrieux