为什么std::make_unique需要初始化成员std::unique数组,以及如何解决C++11?

在下面的代码中,为什么std::make_unique需要初始化Foo::up_
具体来说,为什么不初始化Foo::up_new Bar(...)在注释掉的代码- -工作?

#include <iostream>
#include <memory>

enum E {
  Y = 0,
  Z = 1,
  NUM_E
};

class Bar {
public: // Functions
  Bar( const int& i, const int& j ) : i_(i), j_(j) { }

public: // Objects
  int i_;
  int j_;
};

class Foo {
public: // Functions
  Foo();

  void reset( const int& Yi, const int& Yj,
              const int& Zi, const int& Zj );

public: // Objects
  std::unique_ptr<Bar> up_[NUM_E];
};

Foo::Foo()
  : up_{ std::make_unique<Bar>( 42, 43 ),
         std::make_unique<Bar>( 44, 45 ) }
//  : up_{ new Bar( 42, 43 ),
//         new Bar( 44, 45 ) } // err: could not convert from Bar* to unique_ptr
{ }

void Foo::reset( const int& Yi, const int& Yj,
                 const int& Zi, const int& Zj ) {
  up_[Y].reset( new Bar( Yi, Yj ) );
  up_[Z].reset( new Bar( Zi, Zj ) );
}

int main( int argc, char* argv[] ) {
  (void)argc;
  (void)argv;
  Foo foo;

  std::cout << foo.up_[Y]->i_ << std::endl;
  std::cout << foo.up_[Y]->j_ << std::endl;
  std::cout << foo.up_[Z]->i_ << std::endl;
  std::cout << foo.up_[Z]->j_ << std::endl;

  foo.reset( 1, 2, 3, 4 );

  std::cout << foo.up_[Y]->i_ << std::endl;
  std::cout << foo.up_[Y]->j_ << std::endl;
  std::cout << foo.up_[Z]->i_ << std::endl;
  std::cout << foo.up_[Z]->j_ << std::endl;

  return 0;
}
$ g++ --version && g++ --std=c++14 ./main.cpp && ./a.out
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

42
43
44
45
1
2
3
4

一个人如何解决这个问题C++11,哪里std::make_unique似乎不可用?

$ g++ --version && g++ --std=c++11 ./main.cpp && ./a.out
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

./main.cpp: In constructor ‘Foo::Foo()’:
./main.cpp:31:10: error: ‘make_unique’ is not a member of ‘std’
   : up_{ std::make_unique<Bar>( 42, 43 ),
          ^~~
./main.cpp:31:30: error: expected primary-expression before ‘>’ token
   : up_{ std::make_unique<Bar>( 42, 43 ),
                              ^
./main.cpp:32:10: error: ‘make_unique’ is not a member of ‘std’
          std::make_unique<Bar>( 44, 45 ) }
          ^~~
./main.cpp:32:30: error: expected primary-expression before ‘>’ token
          std::make_unique<Bar>( 44, 45 ) }
                              ^

回答

1. 构造函数unique_ptr( pointer p )被标记为explicit,防止unique_ptr在数组列表初始化时隐式构造 的实例。

2.std::make_unique从 C++14 开始可用。

在 C++11 中,针对这两点的可能解决方案是显式构造一个实例,例如std::unique_ptr<Bar>(new Bar( 42, 43 )).


以上是为什么std::make_unique需要初始化成员std::unique数组,以及如何解决C++11?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>