- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个 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/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 6年前关闭。 Improve this qu
我有实体: @Entity @Table(name = "CARDS") public class Card { @ManyToOne @JoinColumn(name = "PERSON_I
我正在尝试计算二维多边形的表面法线。我正在使用 OpenGL wiki 中的 Newell 方法来计算表面法线。 https://www.opengl.org/wiki/Calculating_a_S
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 关闭 7 年前。 Improve
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 9 年前。 Improve this
我这里有以下 XML: Visa, Mastercard, , , , 0, Discover, American Express siteonly, Buyer Pay
即将发生的 Google 政策变更迫使我们实现一个对话框,以通知欧盟用户有关 Cookie/设备标识符用于广告和分析的情况。我只想向欧盟用户显示此对话框。我不想使用额外的权限(例如 android.p
本文分享自华为云社区《华为大咖说 | 企业应用AI大模型的“道、法、术” ——道:认知篇》,作者:华为云PaaS服务小智。 本期核心观点 上车:AGI是未来5~10年内,每个人都无法回避的技
我有一个与酒精相关的网站,需要先验证年龄,然后才能让他们进入该网站。我使用 HttpModule 来执行此操作,该模块检查 cookie,如果未设置,我会将它们重定向到验证页面。我验证他们的年龄并存储
在欧盟,我们有一项法律,要求网页请求存储 cookie 的许可。我们大多数人都了解 cookie 并同意它们,但仍然被迫在任何地方明确接受它们。所以我计划编写这个附加组件(ff & chrome),它
以下在 C 和/或 C++ 中是否合法? void fn(); inline void fn() { /*Do something here*/ } 让我担心的是,第一个声明看起来暗示函数将被定义
我是一名优秀的程序员,十分优秀!