0

Given a class like this:

class C {
  T obj;
  T getObject() {
      return obj;
  }
}

Can i prevent the caller making references or pointers, something like this:

int main() {
  C c;
  // don't allow this:
  T &mainObj = c.getObject();
  T *mainObj = &c.getObject();
  // only this:
  T mainObj = c.getObject();
}

So in other words I only want to allow copies of the object (multi-threading pupose).

str0yd
  • 97
  • 11
  • Note that `getObject` already always returns a copy. Taking a pointer to that temporary object is a bad idea (https://godbolt.org/g/X922Qp) but initializing a `T` or `const T&` with it will always be legal. But you cannot prevent references to `T` being created, see the duplicate. – Max Langhof Aug 30 '18 at 12:31
  • All of the usages you want to disallow is undefined behavior anyway (if `mainObj` is ever dereferenced), so I don't see a point of explicitly disallowing them. – Algirdas Preidžius Aug 30 '18 at 12:32
  • @AlgirdasPreidžius: From your argument, I would want to disallow them, as I would prefer compile error instead of runtime UB. – Jarod42 Aug 30 '18 at 12:37
  • @Jarod42 1) If caller of your function does something, that causes UB, it's the fault of the caller. 2) In that case, why didn't the standard committee abolished trying to take reference to (/address of) the return value, if it is returned by value? Wouldn't it make it easier on all of us, no? – Algirdas Preidžius Aug 30 '18 at 12:49
  • @AlgirdasPreidžius: Some (old) rules come from the existing (at the epoch) implementation and complexity to diagnose the problem easily, compatibility with C, ... For example, missing return in non void function is compilable even if UB (We got generally a warning though). If there exist valid case, we cannot prohibit it. So unfortunately, we have to work with "dangerous" language. It is legitimate to try to secure our class from mis-usage. OP wants to protect concurrent access to same resource, [tag:Rust] for example allows that protection from the language rule. – Jarod42 Aug 30 '18 at 13:33

0 Answers0