【问题标题】:C++ template member initialization: move-construction with rvalue but reference with lvalueC ++模板成员初始化:使用右值进行移动构造,但使用左值进行引用
【发布时间】:2019-09-16 21:02:08
【问题描述】:

我的类的构造函数初始化引用成员。我怎样才能安全地传递临时对象以初始化这些引用成员?

我有一类对象和对这些对象执行的操作类。这些操作都派生自提供公共接口的抽象基类。否则,这些操作可能包含用于特定实现的大量附加信息。

class Object;

class Operation {
  public:
  virtual void do_something( Object& obj ) = 0;
  /* ... */
}

class FooOperation : public Operation { /*...*/ }
class BarOperation : public Operation { /*...*/ }
class BazOperation : public Operation { /*...*/ }

我也想组合操作。一种正确的方法是使用以下类:

class ComposedOperation : Operation {

  private:

    const Operation& m_op1; const Operation& m_op2;

  public:

    ComposedOperation( const Operation& op1, const Operation& op2 )
    : m_op1(op1), m_op2( op2 ) { };

    void do_something( Object& obj ) override 
    { m_op1.do_something(obj); m_op2.do_something(obj); }
}

问题是组合操作只能绑定左值引用。像下面这样的组合会很危险:

auto op = ComposedOperation( BarOperation(), ComposedOperation( FooOperation(), BazOperation() ) );

如何让班级知道第一个/第二个操作是左值还是右值?最好不要重载构造函数。我想知道模板是否可以在这里提供帮助。

【问题讨论】:

标签: c++ templates deep-copy rvalue shallow-copy


【解决方案1】:

我认为有两种选择:

  1. 将所有操作存储在树之外的某个地方,并确保它们的寿命比对它们的引用长。

  2. 让每个 Operation 拥有自己的子节点,并按值或在 unique_ptrs 中存储它们。

选项 1 在某些情况下可能有用(如果您在某处有操作注册表,并且 Operation 树只是一个组织事物)。但是,从您的使用示例来看,情况似乎并非如此。

选项 2 肯定更简单,实现移动语义应该可以避免任何性能问题。

如果您确实需要避免在特定实例中复制/移动,您可以创建一个 Ref 包装器,该包装器通过引用存储 Operation,并实现 Operation 接口本身。您显然需要在使用它时自己确保正确的生命周期。

所以(大约):

template<class A, class B>
struct FooOperation {
    A a; B b;

    // ... implement operation concept
};

template<class T>
struct Ref {
    T& t;

    // ... implement operation concept
};

auto a = BarOperation();
auto b = FooOperation<Ref<A>, B>(Ref(a), BazOperation());

或者如果我们需要运行时多态性:

struct FooOperation : Operation {
    std::unique_ptr<Operation> a, b;

    // ... implement operation interface
};

struct Ptr : Operation {
    Operation* t;

    // ... implement operation interface
};

auto a = std::make_unique<BarOperation>();
auto b = FooOperation(std::make_unique<Ptr>(a), std::make_unique<BazOperation>());

【讨论】:

    【解决方案2】:

    我可能很笨,但我不明白你的原因

    auto op = ComposedOperation( BarOperation(), ComposedOperation( FooOperation(), BazOperation() ) );
    

    将是“危险的”,以及为什么需要区分左值和右值。

    也许您说的是旧的 C++ 版本(我认为是 C++11 之前的版本),其中右值生命周期没有被扩展以匹配引用的范围?

    编辑:我输入了您的代码并尝试编译它,并进行了一些小的修改,例如在需要的地方添加 const 并将继承公开。

    class Object {
      public:
      int i;
    };
    
    class Operation {
      public:
      virtual void do_something( Object& obj ) const = 0;
      /* ... */
    };
    
    class FooOperation : public Operation { void do_something( Object& obj )const{obj.i++;} };
    class BarOperation : public Operation { void do_something( Object& obj )const{obj.i+=2;} };
    class BazOperation : public Operation { void do_something( Object& obj )const{obj.i+=4;} };
    
    class ComposedOperation : public Operation {
    
      private:
    
        const Operation& m_op1; const Operation& m_op2;
    
      public:
    
        ComposedOperation( const Operation& op1, const Operation& op2 )
        : m_op1(op1), m_op2( op2 ) { };
    
        void do_something( Object& obj ) const override
        { m_op1.do_something(obj); m_op2.do_something(obj); }
    };
    
    int main(){
      Object obj;
      auto op = ComposedOperation( BarOperation(), ComposedOperation( FooOperation(), BazOperation() ) );
      op.do_something(obj);
      return 0;
    }
    

    当使用没有任何标志的 g++ (8.3.0) 时,这编译没有任何问题。 如果我强制它使用 c++98(或任何早于 c++11/c++0x 的东西),我必须摆脱 main 中的 auto 并用 ComposedOperation 替换它,然后甚至在 c++98 中它编译。即使使用 -pedantic 和 -Wall 我也没有任何警告。 我也可以运行二进制文件,它干净地退出。

    Edit2:我使用 -fsanitize 收到的错误消息:

    julien@jeannot:~/tmp$ g++ -std=c++17 -g -pedantic -fsanitize=address test.cpp
    julien@jeannot:~/tmp$ ./a.out
    =================================================================
    ==30438==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffdd41d8720 at pc 0x561189efd8de bp 0x7ffdd41d8690 sp 0x7ffdd41d8688
    READ of size 8 at 0x7ffdd41d8720 thread T0
        #0 0x561189efd8dd in ComposedOperation::do_something(Object&) const /home/julien/tmp/test.cpp:30
        #1 0x561189efd4ac in main /home/julien/tmp/test.cpp:36
        #2 0x7f3f97e4509a in __libc_start_main ../csu/libc-start.c:308
        #3 0x561189efd159 in _start (/home/julien/tmp/a.out+0x1159)
    
    Address 0x7ffdd41d8720 is located in stack of thread T0 at offset 96 in frame
        #0 0x561189efd224 in main /home/julien/tmp/test.cpp:33
    
      This frame has 6 object(s):
        [32, 36) 'obj'
        [96, 104) '<unknown>' <== Memory access at offset 96 is inside this variable
        [160, 168) '<unknown>'
        [224, 232) '<unknown>'
        [288, 312) 'op'
        [352, 376) '<unknown>'
    HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
          (longjmp and C++ exceptions *are* supported)
    SUMMARY: AddressSanitizer: stack-use-after-scope /home/julien/tmp/test.cpp:30 in ComposedOperation::do_something(Object&) const
    Shadow bytes around the buggy address:
      0x10003a833090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a8330a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a8330b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a8330c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a8330d0: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 04 f2 f2 f2
    =>0x10003a8330e0: f2 f2 f2 f2[f8]f2 f2 f2 f2 f2 f2 f2 f8 f2 f2 f2
      0x10003a8330f0: f2 f2 f2 f2 f8 f2 f2 f2 f2 f2 f2 f2 00 00 00 f2
      0x10003a833100: f2 f2 f2 f2 f8 f8 f8 f2 f3 f3 f3 f3 00 00 00 00
      0x10003a833110: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a833120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      0x10003a833130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    Shadow byte legend (one shadow byte represents 8 application bytes):
      Addressable:           00
      Partially addressable: 01 02 03 04 05 06 07 
      Heap left redzone:       fa
      Freed heap region:       fd
      Stack left redzone:      f1
      Stack mid redzone:       f2
      Stack right redzone:     f3
      Stack after return:      f5
      Stack use after scope:   f8
      Global redzone:          f9
      Global init order:       f6
      Poisoned by user:        f7
      Container overflow:      fc
      Array cookie:            ac
      Intra object redzone:    bb
      ASan internal:           fe
      Left alloca redzone:     ca
      Right alloca redzone:    cb
    ==30438==ABORTING
    

    我一直在玩不同的变体,同时在构造函数/析构函数和 do_something 中添加一些 cout。似乎临时对象在行尾但在 do_something 行之前被破坏。如果我将所有内容放在一行中

    ComposedOperation( BarOperation(), ComposedOperation( FooOperation(), BazOperation() ) ).do_something(obj);
    

    然后事情得到足够的扩展,我得到了正确的顺序:

    julien@jeannot:~/tmp$ ./a.out 
    Operation construction
    Operation construction
    Operation construction
    ComposedOperation construction
    Operation construction
    Operation construction
    ComposedOperation construction
    ComposedOperation doing something
    ComposedOperation doing something
    ComposedOperation destruction
    Operation destruction
    Operation destruction
    ComposedOperation destruction
    Operation destruction
    Operation destruction
    Operation destruction
    7
    

    所以正确的解释应该是对临时对象的引用只允许扩展到完整表达式的范围,而不是对象的范围。

    有点令人困惑的是,与

    const Operation& foo = FooOperation();
    const Operation& baz = BazOperation();
    const ComposedOperation& tmp = ComposedOperation( foo, baz );
    const Operation& bar = BarOperation();
    ComposedOperation op = ComposedOperation( bar, tmp );
    

    您确实会延长临时对象的生命周期,直到 main() 结束。

    所以,作为一个结论,我相信,我的建议是:用 unique_ptr 替换您的引用。然后您可以轻松地使用克隆功能并确保您不会获得悬空引用:

    #include <iostream>
    #include <memory>
    
    class Object {
      public:
      int i=0;
    };
    
    class Operation {
      public:
      virtual void do_something( Object& obj ) const = 0;
      /* ... */
      Operation() { std::cout << "Operation construction\n"; };
      std::unique_ptr<Operation> clone() const {
        return std::unique_ptr<Operation>(clone_impl());
      };
      virtual Operation* clone_impl() const = 0;
    };
    
    class FooOperation : public Operation { FooOperation* clone_impl() const {return new FooOperation();} void do_something( Object& obj )const{obj.i++;} };
    class BarOperation : public Operation { BarOperation* clone_impl() const {return new BarOperation();}; void do_something( Object& obj )const{obj.i+=2;} };
    class BazOperation : public Operation { BazOperation* clone_impl() const {return new BazOperation();} void do_something( Object& obj )const{obj.i+=4;} };
    
    class ComposedOperation : public Operation {
    
      private:
    
        std::unique_ptr<Operation> m_op1; std::unique_ptr<Operation> m_op2;
    
      public:
    
        ComposedOperation( const Operation& op1, const Operation& op2 )
        : m_op1(op1.clone()), m_op2(op2.clone()) { std::cout << "ComposedOperation construction\n"; };
    
        ComposedOperation* clone_impl() const {return new ComposedOperation(*m_op1->clone(),*m_op2->clone());}
    
        void do_something( Object& obj ) const override
        { std::cout<<"ComposedOperation doing something\n"; m_op1->do_something(obj); m_op2->do_something(obj); }
    };
    
    int main(){
      Object obj;
      const ComposedOperation& op = ComposedOperation( BarOperation(), ComposedOperation( FooOperation(), BazOperation() ) );
      op.do_something(obj);
      std::cout << obj.i << std::endl;
      return 0;
    }
    

    如果您希望同时能够在传递一个您知道会存在足够长的简单左值时避免复制,您可以通过重载 ComposedOperation 构造函数来做到这一点,例如:

    ComposedOperation( const Operation& op1, const Operation& op2 )
    : m_op1(op1.clone()), m_op2(op2.clone()) { };
    ComposedOperation( const Operation&& op1, const Operation&& op2 )
    : m_op1(op1.move()), m_op2(op2.move()) { };
    

    你应该有类似的东西

    FooOperation* move_impl() const {return new FooOperation(std::move(*this));}
    

    【讨论】:

    • 旧 C++ 的行为有多远?
    • 我认为它只在 C++11 和更新版本中有效,但我的测试表明它甚至在最旧的版本中也有效。除非您不同意我为使其编译而必须做的一些小修改。
    • 谢谢。但是,我遇到了分段错误,使用g++ -std=c++17 -g -pedantic 和 gcc 8.3 编译它,所以我认为您的示例不可移植。 Valgrind 抱怨最后一行 do_something。
    • 如果我在最后一个 do_something 之后添加 std::cout &lt;&lt; obj.i &lt;&lt; std::endl; (并在 Object() 中初始化 i ),我确实得到了 7 。直接或在 gdb 或 valgrind 下运行(未检测到泄漏)不会改变任何内容。你能复制粘贴确切的valgrind抱怨吗?并添加一个 gdb 回溯?万一这很重要,我在带有 Linux 4.19.0-5-amd64 的 Debian Buster 上对其进行了测试。
    • 如果你用`-fsanitize=address`编译你的机器会发生什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多