클래스에 공용 데이터 멤버가 없으면이 작업이 수행 될 수 있습니다.
기본적으로 래퍼의 구성을 제한하는 것이 아니라 (임시 보관 값인 경우에만 사용 가능)을 사용할 수 있습니다.모두 메서드를 오버로드하고 const &을 참조하는 메서드를 삭제하거나 비공개로 만들어이 작업을 수행 할 수 있습니다.
class Wrapper
{
public:
Wrapper() = default;
Wrapper(const std::string& name) : name(name) {}
void process() && { std::cout << "Greetings from " << name << std::endl; }
// Only temporary instances of this class are allowed!
void process() const & = delete;
private:
std::string name;
};
그리고 일부 사용 사례 :
Wrapper("John").process(); // intended use case
Wrapper j; // create whatever you want
j.process(); // error C2280: 'void Wrapper::process(void) const &': attempting to reference a deleted function
std::move(j).process(); // this is still possible
const Wrapper& t = Wrapper(); // bind the temporary to a const reference - not a problem because ...
t.process(); // error C2280: 'void Wrapper::process(void) const &': attempting to reference a deleted function
명백한 단점은 다음과 같습니다
- 당신은 모든 공공 멤버 함수를 오버로드 할
다음은 간단한 예입니다.
- 오류 메시지가 지연되어 매우 유익하지 않습니다.
비슷한 점이 표준에서 수행되었습니다. std :: reference_wrapper에 대한 make 루틴 do not accept temporaries. 그들은 다른 미묘 고려
참고 : 과부하는 const를 T & & 대신 T & &를 사용합니다. 이 경우에도 중요 할 수 있습니다. 래퍼가 의도적으로 noncopyable 수 있도록 설계되어 예를 들어, 당신은이 경우
const Wrapper make_wrapper();
대신
Wrapper make_wrapper();
같은 루틴을 사용, 당신은 대체 할 수 있습니다
void process() &&;
void process() const &&;
인스턴스가 힙이 아닌 스택에 만 생성되도록 허용 할 수 있습니까? –
아니요, 임시 사용자로만 사용하십시오. 스택 상에 그러한 인스턴스를 생성하는 것은 여전히 위험합니다. –
때때로 최상의 예방 조치는 문서에서 "do not do X"의 주석입니다. –