how to forbid assignment to not reference variables?

一笑奈何 提交于 2019-12-10 18:09:40

问题


I fear it's a dumb question but...

Someone can suggest me a way to force that a return value from a function (or a method), that return a reference to an internal static variable or a member of the class/struct, is assigned only to reference variables ?

I try to explain what I desire with a minimal example.

Given the following code, with a function wrapValue() that return a reference to the internal static variable,

int & wrapValue (int v0)
 {
   static int val;

   return val = v0;
 }

int main ()
 {
   // how to permit this ...
   int & v0 { wrapValue(0) };

   // ... but forbid this ...
   int   v1 { wrapValue(1) };

   int   v2;

   // ... and this ?
   v2 = wrapValue(2);
 }

there is a way to permit the initialization of v0 (and bound v0 to the static variable) and forbid the initialization of v1 and the assignment of v2 (without bounding v1 and v2 to the static variable) ?

And if it's impossible with the current C++ standard, as I fear, someone can suggest me an alternative way (but not too complex: I intend use it in a library that I want to maintain simple) to forbid an unbounded assignment ?


回答1:


This solution is somewhat tricky but it works (I think) as you expect:

#include <iostream>

struct int_wrapper {
    int value;
    int_wrapper &operator=(int value) {
        this->value = value;
        return *this;
    }
    operator int&() {
        return value;
    }
    operator int() {
        return value;
    }
};

int_wrapper& wrapValue (int v0) {
   static int_wrapper val;
   return val = v0;
}

int main () {
   // how to permit this ...
   int & v0 = wrapValue(0);

   // ... but forbid this ...
   //int   v1 { wrapValue(1) }; // call ambigious

   int   v2;
   (void)v0;
   (void)v2;

   // ... and this ?
   //v2 = wrapValue(2); // call ambigious
}

[live demo]




回答2:


As far as I know int is copyable, so people can copy if they like; you cannot prevent this. However, you could create a wrapper class that is non-copyable.

class NonCopyableInt
{
    int val;
public:
    NonCopyableInt(int val) : val(val) {}
    NonCopyableInt(NonCopyableInt&) = delete;
    int& value() { return val; }
    // todo: add some nice operators and functions such as assignment from int
}

NonCopyableInt& wrapValue (int v0)
{
    static NonCopyableInt val;
    return val = v0;
}

However, people could always copy the return value from value() so you end up with the same problem. And it feels really clunky and meh.



来源:https://stackoverflow.com/questions/41076212/how-to-forbid-assignment-to-not-reference-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!