이로 인해 컴파일러 오류가 발생하지 않지만 런타임 오류가 발생합니다. 잘못된 시간을 측정하는 대신 허용 가능한 예외가 발생합니다.
보호하려는 모든 생성자 set(guard)는 호출 되는 기본 인수가 필요합니다 .
struct Guard {
Guard()
:guardflagp()
{ }
~Guard() {
assert(guardflagp && "Forgot to call guard?");
*guardflagp = 0;
}
void *set(Guard const *&guardflag) {
if(guardflagp) {
*guardflagp = 0;
}
guardflagp = &guardflag;
*guardflagp = this;
}
private:
Guard const **guardflagp;
};
class Foo {
public:
Foo(const char *arg1, Guard &&g = Guard())
:guard()
{ g.set(guard); }
~Foo() {
assert(!guard && "A Foo object cannot be temporary!");
}
private:
mutable Guard const *guard;
};
특성은 다음과 같습니다.
Foo f() {
// OK (no temporary)
Foo f1("hello");
// may throw (may introduce a temporary on behalf of the compiler)
Foo f2 = "hello";
// may throw (introduces a temporary that may be optimized away
Foo f3 = Foo("hello");
// OK (no temporary)
Foo f4{"hello"};
// OK (no temporary)
Foo f = { "hello" };
// always throws
Foo("hello");
// OK (normal copy)
return f;
// may throw (may introduce a temporary on behalf of the compiler)
return "hello";
// OK (initialized temporary lives longer than its initializers)
return { "hello" };
}
int main() {
// OK (it's f that created the temporary in its body)
f();
// OK (normal copy)
Foo g1(f());
// OK (normal copy)
Foo g2 = f();
}
의 경우 f2, f3및 반환 "hello"싶어하지 않을 수 있습니다. 던지는 것을 방지하기 위해를 재설정 guard하여 복사본의 소스 대신 우리를 보호하도록 하여 복사본의 소스를 임시로 허용 할 수 있습니다 . 이제 위의 포인터를 사용하는 이유도 알 수 있습니다. 이는 유연성을 제공합니다.
class Foo {
public:
Foo(const char *arg1, Guard &&g = Guard())
:guard()
{ g.set(guard); }
Foo(Foo &&other)
:guard(other.guard)
{
if(guard) {
guard->set(guard);
}
}
Foo(const Foo& other)
:guard(other.guard)
{
if(guard) {
guard->set(guard);
}
}
~Foo() {
assert(!guard && "A Foo object cannot be temporary!");
}
private:
mutable Guard const *guard;
};
의 특성 f2, f3그리고 대한이 return "hello"항상 지금 // OK.