gpt4 book ai didi

c++ - c++ 11为调用者构造一个对象

转载 作者:行者123 更新时间:2023-12-01 15:07:05 24 4
gpt4 key购买 nike

我有一些Foo结构,需要了解其他一些对象的状态才能初始化,因此我为此创建了一个工厂方法:

struct Foo {
Foo(int x) : x_(x) {}

int x_;
};

struct FooFactory {
Foo MakeFoo() {
return Foo(++counter);
}

int counter = 0;
};

因此,尽管 call 者只能执行 Foo(++factory.counter),但只说 factory.MakeFoo()则更加清洁。

但是此代码需要复制,并说我们要避免这种情况。我们可以改用move构造函数。
struct Foo {
Foo(int x) : x_(x) {}
Foo(Foo& foo) = delete;
Foo(Foo&& foo) : Foo(foo.x_) { foo.x_ = 0; }

int x_;
};

struct FooFactory {
Foo MakeFoo() {
return Foo(++counter);
}

int counter = 0;
};

哪个可行,但看起来仍然比我想要的更多。诸如 Foo foo = factory.MakeFoo()之类的东西仍然会在 MakeFoo()内部创建一个临时项,然后通过其move构造函数构造 foo

有没有一种方法可以编写此代码,以便 MakeFoo直接构造到分配给它的内容中?

最佳答案

是的,使用braced-init-list return直接初始化目标对象:

struct FooFactory {
Foo MakeFoo() {
return {++counter};
}
// ...
};
请注意,如果 Foo的1参数构造函数是 explicit,则此方法将无效。

6.6.3 [stmt.return]:

[...] A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list. [...]

关于c++ - c++ 11为调用者构造一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24331640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com