通过复制 Abseil 示例使用 STL 实现工厂函数

Implementing Factory Function with STL by Replicating Abseil Example

尝试通过使用标准模板库复制示例来更好地理解 Tip of the Week #42: Prefer Factory Functions to Initializer Methods。 OP提供示例代码:

// foo.h
class Foo {
 public:
  // Factory method: creates and returns a Foo.
  // May return null on failure.
  static std::unique_ptr<Foo> Create();

  // Foo is not copyable.
  Foo(const Foo&) = delete;
  Foo& operator=(const Foo&) = delete;

 private:
  // Clients can't invoke the constructor directly.
  Foo();
};

// foo.c
std::unique_ptr<Foo> Foo::Create() {
  // Note that since Foo's constructor is private, we have to use new.
  return absl::WrapUnique(new Foo());
}

在尝试复制示例时,我在 foo.c 部分使用了不同的方法:

std::unique_ptr<Foo> Foo::Create() {
    // Attempt to create using std::unique_ptr instead of absl::WrapUnique
    return std::unique_ptr<Foo>(new Foo());
}

使用以下命令编译会导致链接器命令失败

$ clang++  -g -Wall -std=c++11 -fsanitize=address foo.cc -o Foo

Undefined symbols for architecture arm64:
  "Foo::Foo()", referenced from:
      Foo::Create() in robots-cda3fd.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

想想我在这里错过了什么?谢谢!

你还需要定义Foo::Foo()

  1. 在页眉中你可以Foo() = default,甚至在私人部分
  2. 在 cpp 中你可以做 Foo::Foo() = defaultFoo::Foo() {}