如何禁止采用 const 引用的函数中的临时变量?
How to disallow temporaries in functions taking const references?
背景:
假设我有这样的东西:
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
}
之所以不能只重载operator<<
,是因为它更人性化,而且视图用于将数据传递给SQL,所以必须转义刻度和其他一些字符。
问题:
有人可能想做这样的事情:
auto view = item_view(2);
std::cout << view;
这似乎是未定义的行为。
问题:
如何防止从临时对象构造 item_view
?
您可以提供一个更适合临时对象的额外重载,然后将其删除。例如:
#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
}
背景:
假设我有这样的东西:
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
}
之所以不能只重载operator<<
,是因为它更人性化,而且视图用于将数据传递给SQL,所以必须转义刻度和其他一些字符。
问题:
有人可能想做这样的事情:
auto view = item_view(2);
std::cout << view;
这似乎是未定义的行为。
问题:
如何防止从临时对象构造 item_view
?
您可以提供一个更适合临时对象的额外重载,然后将其删除。例如:
#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
}