gpt4 book ai didi

c++ - this* 在 make_unique 中的用法

转载 作者:太空狗 更新时间:2023-10-29 20:01:52 38 4
gpt4 key购买 nike

我有一个 Factory 的小例子设计模式,我对这部分很感兴趣:

std::make_unique< A >(*this)

...尤其是*this .

这是否意味着 clone()方法返回 std::unique_ptr哪个指向工厂类的成员?和 createInstance()始终返回 Factory 的同一成员类(class)?

我只是很困惑std::make_unique< A >(*this)应该这样做,因为A在构造函数中有 std::string ,而不是指向自身的指针。

class Base {
public:
virtual ~Base() {}
virtual std::unique_ptr<Base> clone() = 0;
virtual void print() = 0;
};

class A: public Base {
std::string name_;
public:
A(std::string name ){name_ = name;};
std::unique_ptr<Base> clone() override{
return std::make_unique<A>(*this);
};
void print( ) override{
std::cout << "Class A: " << name_;
};
virtual ~A(){};
};

class Factory{
std::unique_ptr<A> type = std::make_unique<A>("MyName");
public:
std::unique_ptr<Base> createInstance(){
return type->clone();
}
};

int main(){
Factory factory;
auto instance = factory.createInstance();
instance->print();
}

最佳答案

std::make_unique<A>(*this)基本上等同于:

unique_ptr<A>(new A(*this))

clone() , *this是对 A 的左值引用, 所以你正在构建一个 A来自(左值引用)A (在 std::make_unique 内),因此您使用的是 A 的隐式声明的复制构造函数:

A(A const&);

因此,您实际上是在将当前对象复制到新分配的内存块中。

createInstance使用 clone() ,您正在创建 type 的“拷贝”每次你打电话createInstance .

关于c++ - this* 在 make_unique 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570066/

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