Re: Defeating (N)RVO
peter koch larsen schrieb:
(In real life, cheater is an "error return code" and I want to verify
that its value has been examined. RVO prevents this for obvious
reasons).
I don't see, how RVO is related to that issue. Shouldn't something like
the following implementation work independent on the situation whether
(N)RVO is
in action or not?
Greetings from Bremen,
Daniel Kr?gler
#include <stdlib.h>
#include <algorithm>
#include <iostream>
template <typename RetType>
struct cheater {
private:
RetType value_;
int* refCnt_;
mutable bool hasRead_;
void swap(cheater& other) {
std::swap(value_, other.value_);
std::swap(refCnt_, other.refCnt_);
std::swap(hasRead_, other.hasRead_);
}
public:
cheater(RetType result) :
value_(result), refCnt_(new int(1)), hasRead_(false)
{
}
cheater(const cheater& src) :
value_(src.value_), refCnt_(src.refCnt_), hasRead_(src.hasRead_)
{
++*refCnt_;
}
cheater& operator=(const cheater& src)
{
cheater(src).swap(*this);
return *this;
}
~cheater()
{
if (--*refCnt_ == 0) {
delete refCnt_;
if (!hasRead_) {
abort();
}
}
}
operator RetType() const {
hasRead_ = true;
return value_;
}
};
enum test_signal { wonderful, nasty };
cheater<test_signal> foo() {
return wonderful;
}
int main() {
foo() /* == wonderful*/;
std::cerr << "Should never occur" << std::endl;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]