c++ - 只允许传递指向新对象的指针

标签 c++ c++11

我有抽象类 Managee 和辅助类 Wrapper。指向用于构造 Wrapper 的 Managee 的指针,然后 Wrapper 将接管 Managee。我想确保用户将始终分配新的 Managee。右值引用适合这个目标吗?

包装器定义:

...
Wrapper(Managee * && tmpptr);
Managee & GetManagee();
...

包装器用法:

Wrapper a(new ManageeA()); // ok;
Wrapper b(&a.GetManagee()); // error?    <-----

最佳答案

右值引用没有帮助,因为 &a.GetManagee() 是一个右值。 为什么不采用 std::unique_ptr

Wrapper(std::unique_ptr<Managee> ptr)
  : member_ptr(std::move(ptr)) {}

Managee& GetManagee();

用法:

Wrapper a(make_unique<Managee>(/*args*/));

对于 make_unique,参见 here .

然而,最好的解决方案甚至不允许用户在堆栈上创建 Managee 的派生类型——这可以通过工厂函数来完成(当然是使用 std::unique_ptr) 并将构造函数设为私有(private):

class SomeClass : public Managee{
public:
  static std::unique_ptr<SomeClass> create(){
    return make_unique<SomeClass>();
  }
private:
  SomeClass(){}
  // other ctors
};

关于c++ - 只允许传递指向新对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13213914/

相关文章:

c++ - 对类成员使用智能指针

c++ - C++0x什么时候发布,什么时候成为事实上的标准?

c++ - 使用 this = new Foo()? 从内部将一个对象的实例设置为另一个对象的实例?

c++ - Visual Studio 17 用户关键字冲突(?)

c++ - 预处理器错误 C++

c++ - for循环在Rcpp中崩溃

c++ - 检查该函数是否已在 gtest 中调用

c++ - 由于 Sleep 函数,线程终止了进程

C++ std::vector<std::string> 迭代器段错误

c++ - 如何使用元编程过滤 const 类型和非 const 类型?