C ++静态工厂构造函数 [英] C++ static factory constructor

查看:79
本文介绍了C ++静态工厂构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行仿真,因此需要创建多个相当相似的模型。我的想法是拥有一个名为Model的类,并使用静态工厂方法来构建模型。例如; Model :: createTriangle Model :: createFromFile 。我从以前的Java代码中汲取了这个想法,并正在寻找在C ++中实现该想法的方法。

I am in the process of making a simulation and it requires the creation of multiple, rather similar models. My idea is to have a class called Model and use static factory methods to construct a model. For example; Model::createTriangle or Model::createFromFile. I took this idea from previous java code and was looking for ways to implement this in C++.

这是我到目前为止想出的内容:

Here is what I came up with so far:

#include <iostream>

class Object {
    int id;

public:
    void print() { std::cout << id << std::endl; }

    static Object &createWithID(int id) {
        Object *obj = new Object();

        obj->id = id;

        return *obj; 
    }
};

int main() {
    Object obj = Object::createWithID(3);

    obj.print();

    return 0;
}

对此有一些疑问:


  • 这是一种可接受的,干净的制造对象的方式吗?

  • 返回的引用是否始终确保正确删除了对象?

  • 有没有没有指针的方法吗?

推荐答案

您的代码当前包含内存泄漏:使用 new 创建的任何对象都必须使用 delete 清除。 createWithID 方法最好应该根本不使用 new 并且看起来像这样:

Your code currently contains a memory leak: any object created using new, must be cleaned up using delete. The createWithID method should preferably not use new at all and look something like this:

static Object createWithID(int id) 
{
    Object obj;
    obj.id = id;
    return obj; 
}

这似乎需要该对象的附加副本,但实际上返回值优化通常会导致此副本被优化掉。

This appears to require an additional copy of the object, but in reality return value optimization will typically cause this copy to be optimized away.

这篇关于C ++静态工厂构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆