防止创建临时对象 [英] Prevent the creation of temporary objects
问题描述
我有一个五年前在这里问过的相同问题:
不允许创建临时对象
I have the same question that was asked over here five years ago: Disallowing creation of the temporary objects
再次询问的原因是,我对C ++ 11和C ++ 14技术特别感兴趣
The reason I am asking it again is that I am specifically interested in C++11 and C++14 techniques for preventing the construction of temporaries.
一个想法是使用此值的右值引用:
One idea is to use "rvalue reference for *this":
class ScopedLock
{
public:
void enable() && = delete;
void enable() &
{
is_enabled = true;
}
~ScopedLock()
{
if (!is_enabled) {
std::cerr << "ScopedLock misuse." << std::endl;
std::terminate();
}
}
private:
bool is_enabled = false;
};
int main()
{
// OK
ScopedLock lock;
lock.enable();
// Compilation error.
ScopedLock().enable();
// std::terminate
ScopedLock();
// std::terminate
ScopedLock lock;
std::cout << "Y" << std::endl;
}
也许有更好的方法?
推荐答案
以下是相同的问题。我对此不值得多加赞赏,因此请考虑对原始答案进行投票。
Here are C++11 versions of two great answers to the same question. I don't deserve much credit for this, so consider voting for the original answers instead.
user1773602的answer
user1773602's answer
该想法是定义一个具有相同名称的已删除函数作为类:
The idea is defining a deleted function with de same name as the class:
class ScopedLock {
// ...
};
void ScopedLock(...) = delete;
用法不寻常,可能很不方便:
The usage is unusual and this might be (very?) inconvenient:
class ScopedLock a; // OK :-| but requires keyword 'class'
ScopedLock b; // Compiler error :-(
ScopedLock(); // Compiler error :-)
Johannes Schaub - litb's answer
如果您不介意遇到运行时错误(例如OP似乎会这样做)
If you don't mind having a runtime error (like the OP seems to do) rather than a compile time error then you can try this.
基本思想是,临时绑定到 ScopedLock $ c的参数$ c>的构造函数将在
ScopedLock
对象之前或之后销毁,具体取决于后者是否是临时对象。
The basic idea is that a temporary bound to an argument of ScopedLock
's constructor will be destroyed before or after the ScopedLock
object depending on whether the later is a temporary or not.
class ScopedLock {
bool flag_ = true;
struct Flag {
bool* flag;
~Flag() {
*flag = false;
}
};
public:
ScopedLock(Flag&& f = Flag()) {
f.flag = &flag_;
}
~ScopedLock() {
if (flag_) {
std::cerr << "ScopedLock misuse\n.";
std::terminate();
}
}
};
有了这个,我们有了
ScopedLock a; // OK
ScopedLock(); // Runtime error
这篇关于防止创建临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!