11

This is really a terribly silly question to which the answer is probably a simple "no", but I'm going to ask in case there is because it would be quite nice.

I can do this, behaviour is exactly as desired:

struct A { int x; };

A inc(A a) {
    a.x += 1;
    return a;
}

inc({ 1 });

where the fact that { 1 } is a temporary forces that it won't be reused, because it has been left invalid by inc() (because of the use of the move constructor -- please correct me if I am wrong about this!).

But what if I am bad at remembering what { 1 } was supposed to stand for, so I make a variable for it, but I still want to force the requirement that it can't be used twice (I'm trying to make it just like a temporary, but named):

A a = { 1 };
inc(a);
inc(a);

No variation of reference type for a will lead the compiler to complain about the double use -- but the move constructor has been precluded by a not being a temporary.

Is there a solution?

3
  • 1
    Not sure how much it will help, but you could technically build a UseOnce<T> with an operator T (or get function) that gives an error the second time it's called.
    – chris
    Dec 30, 2013 at 8:19
  • Just curious - can you give an example where this "use once" behavior is useful? Where would you use this?
    – tucuxi
    Dec 30, 2013 at 8:24
  • In effect, you want the type of a to change after it is used in particular ways. This is not supported in C++ -- variable types are constant over their scope. There is a name for it, however... but I don't remember it. Dec 30, 2013 at 21:00

5 Answers 5

12

I don't think there's a data type for that, but you can use a minimal nested block to limit the scope of the variable - I do this quite often in my code:

{
  A a = { 1 };
  inc(a);
}
inc(a);  //error, `a` is not in scope
1

You're describing pretty much the functionality of std::move :

A a { 1 };
inc(std::move(a));

And no, the compiler cannot enforce single-use:

A a { 1 };
for (int i = 0; i != 1000; ++i)
  if (g(i)) // Only signature is known, not runtime behavior.
     inc(std::move(a));
0

A (possible) fix is to declare inc to take an rvalue reference specifically:

A inc(A&& a)
{
    a.x += 1;
    return a;
}

When calling it with an lvalue, it will then need to be moved explicitly with std::move to compile:

A a = {1};
inc(a);    // Error: cannot bind lvalue to rvalue
inc(std::move(a));  // Ok

The compiler won't complain about the double use, however, the (explicit) use of std::move should tip off anyone reading the code to not use a again.

0

You could use ref qualifier and then use it like so.

struct A
{
    A(int i): i_(i) {std::cout << "hello "<<i<<"\n"; }
    A inc() && {return A(++i_); }     //ref qualified incrementor. so it can be called only on temporaries. 
    friend int access( A a );    // to access the value
    A& operator=( const A& ) = delete;// don't allow copy
private :
    int i_;
};

int access( A a )
{
    return a.i_;
}

//use case

int main()
{
    //A a{5};    //this becomes useless. only use is to get the value..
    A b = A(10).inc();
    //b.inc();    //not possible
    //b = A( 12 ).inc();    //not possible
    std::cout << "\n val = "<<access( b );
return 0;
}

but this makes your struct a Non-POD.

also this is available in gcc > 4.8.1.

0

it is possible to detect object are used as temporary in runtime.

this is how Mozilla implemented it

Copied from above link. You can search MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER in their git repo for example usage

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* Implementation of macros to ensure correct use of RAII Auto* objects. */

#ifndef mozilla_GuardObjects_h
#define mozilla_GuardObjects_h

#include "mozilla/Assertions.h"
#include "mozilla/NullPtr.h"
#include "mozilla/Types.h"

#ifdef __cplusplus

#ifdef DEBUG

namespace mozilla {
namespace detail {

/*
 * The following classes are designed to cause assertions to detect
 * inadvertent use of guard objects as temporaries. In other words,
 * when we have a guard object whose only purpose is its constructor and
 * destructor (and is never otherwise referenced), the intended use
 * might be:
 *
 *   AutoRestore savePainting(mIsPainting);
 *
 * but is is easy to accidentally write:
 *
 *   AutoRestore(mIsPainting);
 *
 * which compiles just fine, but runs the destructor well before the
 * intended time.
 *
 * They work by adding (#ifdef DEBUG) an additional parameter to the
 * guard object's constructor, with a default value, so that users of
 * the guard object's API do not need to do anything. The default value
 * of this parameter is a temporary object. C++ (ISO/IEC 14882:1998),
 * section 12.2 [class.temporary], clauses 4 and 5 seem to assume a
 * guarantee that temporaries are destroyed in the reverse of their
 * construction order, but I actually can't find a statement that that
 * is true in the general case (beyond the two specific cases mentioned
 * there). However, it seems to be true.
 *
 * These classes are intended to be used only via the macros immediately
 * below them:
 *
 *   MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER declares (ifdef DEBUG) a member
 *     variable, and should be put where a declaration of a private
 *     member variable would be placed.
 *   MOZ_GUARD_OBJECT_NOTIFIER_PARAM should be placed at the end of the
 *     parameters to each constructor of the guard object; it declares
 *     (ifdef DEBUG) an additional parameter. (But use the *_ONLY_PARAM
 *     variant for constructors that take no other parameters.)
 *   MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL should likewise be used in
 *     the implementation of such constructors when they are not inline.
 *   MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT should be used in
 *     the implementation of such constructors to pass the parameter to
 *     a base class that also uses these macros
 *   MOZ_GUARD_OBJECT_NOTIFIER_INIT is a statement that belongs in each
 *     constructor. It uses the parameter declared by
 *     MOZ_GUARD_OBJECT_NOTIFIER_PARAM.
 *
 * For more details, and examples of using these macros, see
 * https://developer.mozilla.org/en/Using_RAII_classes_in_Mozilla
 */
class MOZ_EXPORT GuardObjectNotifier
{
  private:
    bool* statementDone;

  public:
    GuardObjectNotifier() : statementDone(nullptr) { }

    ~GuardObjectNotifier() {
      *statementDone = true;
    }

    void setStatementDone(bool* statementIsDone) {
      statementDone = statementIsDone;
    }
};

class MOZ_EXPORT GuardObjectNotificationReceiver
{
  private:
    bool statementDone;

  public:
    GuardObjectNotificationReceiver() : statementDone(false) { }

    ~GuardObjectNotificationReceiver() {
      /*
       * Assert that the guard object was not used as a temporary.  (Note that
       * this assert might also fire if init is not called because the guard
       * object's implementation is not using the above macros correctly.)
       */
      MOZ_ASSERT(statementDone);
    }

    void init(const GuardObjectNotifier& constNotifier) {
      /*
       * constNotifier is passed as a const reference so that we can pass a
       * temporary, but we really intend it as non-const.
       */
      GuardObjectNotifier& notifier = const_cast<GuardObjectNotifier&>(constNotifier);
      notifier.setStatementDone(&statementDone);
    }
};

} /* namespace detail */
} /* namespace mozilla */

#endif /* DEBUG */

#ifdef DEBUG
#  define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER \
     mozilla::detail::GuardObjectNotificationReceiver _mCheckNotUsedAsTemporary;
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM \
     , const mozilla::detail::GuardObjectNotifier& _notifier = \
         mozilla::detail::GuardObjectNotifier()
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM \
     const mozilla::detail::GuardObjectNotifier& _notifier = \
         mozilla::detail::GuardObjectNotifier()
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL \
     , const mozilla::detail::GuardObjectNotifier& _notifier
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL \
     const mozilla::detail::GuardObjectNotifier& _notifier
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT \
     , _notifier
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT \
       _notifier
#  define MOZ_GUARD_OBJECT_NOTIFIER_INIT \
     do { _mCheckNotUsedAsTemporary.init(_notifier); } while (0)
#else
#  define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL
#  define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT
#  define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT
#  define MOZ_GUARD_OBJECT_NOTIFIER_INIT do { } while (0)
#endif

#endif /* __cplusplus */

#endif /* mozilla_GuardObjects_h */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.