问题 是否存在模仿临时的C ++变量类型?


这真是一个非常愚蠢的问题,答案可能是一个简单的“不”,但我会问,以防万一,因为它会很好。

我可以这样做,行为完全符合要求:

struct A { int x; };

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

inc({ 1 });

事实在哪里 { 1 } 是一种暂时的力量,它不会被重用,因为它已被无效 inc() (因为使用了移动构造函数 - 如果我错了,请纠正我!)。

但是,如果我不记得什么,那该怎么办? { 1 } 应该代表,所以我为它做了一个变量,但我仍然想强制要求它不能被使用两次(我试图使它像一个临时的,但命名):

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

没有参考类型的变化 a 将导致编译器抱怨双重使用 - 但移动构造函数已被排除 a 不是暂时的。

有解决方案吗?


2668
2017-12-30 08:17


起源

不知道它会有多大帮助,但你可以在技术上建立一个 UseOnce<T> 与 operator T (要么 get 函数)在第二次调用时给出错误。 - chris
只是好奇 - 你能举个例子说这个“一次使用”的行为是有用的吗?你会在哪里使用它? - tucuxi
实际上,你想要的类型 a 在以特定方式使用后改变。 C ++不支持这一点 - 变量类型在其范围内是不变的。有一个名字,但是......但我不记得了。 - Yakk - Adam Nevraumont


答案:


我不认为有这样的数据类型,但你可以使用一个最小的嵌套块来限制变量的范围 - 我经常在我的代码中这样做:

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

12
2017-12-30 08:21





你几乎描述了它的功能 std::move :

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

不,编译器不能强制执行单次使用:

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

1
2017-12-30 08:29





(可能的)修复是声明 inc 特别采用右值参考:

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

当用左值调用它时,它将需要显式移动 std::move 编译:

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

编译器不会抱怨双重使用,但是,(显式)使用 std::move 应该提醒任何阅读代码的人不要使用 a 再次。


0
2017-12-30 08:26





你可以使用ref限定符,然后像这样使用它。

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_;
}

//用例

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;
}

但这会使你的结构成为非POD。

这也可以在gcc> 4.8.1中找到。


0
2017-12-30 09:12





可以检测到对象在运行时用作临时对象。

这个 是Mozilla如何实现它

复制自上面的链接。你可以搜索 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER 在他们的 git repo 例如用法

/* -*- 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 */

0
2018-01-06 03:45