C ++对象组合,依赖注入和复制构造函数 [英] C++ Object Composition, Depdendency Injection and Copy Constructors

查看:156
本文介绍了C ++对象组合,依赖注入和复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C ++设计一个称为Entity的类。该实体具有一个指向Vector3D成员的指针,该成员是该实体在3D空间中的位置。构造函数允许将Vector3D类型的指针传递给构造函数,从而可以在类外部实例化Vector3D实例。

I want to design a class in C++ called Entity. That entity has a pointer to a member of Vector3D which is the position of the entity in 3D space. The constructor allows a pointer of type Vector3D to be passed to the constructor, such that the Vector3D instance is instantiated outside of the class.

因为存在指向动态对象的指针。分配对象时,必须重载复制构造函数和赋值运算符以深复制向量。但是,由于向量可以在构造函数中传递,因此它也可以在其他地方使用,因此不能在析构函数中删除。但是,如果通过复制构造函数创建的新实体或使用=运算符分配的新实体,则该实体类必须删除vector的实例,因为它是在Entity类中实例化的。

Because there is a pointer to a dynamically allocated object, the copy constructor and assignment operator must be overloaded to deep copy the vector. However, because the vector can be passed in the constructor, it may also be used elsewhere and so cannot be deleted in the destructor. But if a new Entity created through the copy constructor or assigned with the = operator, the entity class must delete the instance of vector because it was instantiated within the Entity class.

解决此类问题的最佳方法是什么?

What is the best way to solve such problems?

#ifndef ENTITY_H
#define ENTITY_H

#include "Vector3D.h"

class Entity {
public:
    Entity(Vector3D*);
    Entity(const Entity&);
    ~Entity();

    Entity& operator = (const Entity&);
protected:
    Vector3D* vector;
};

#endif


推荐答案

最好的方法是不使用指向 Vector3D 的指针,而是按值使用它。如果我怀疑 Vector3D (大约3个浮点数或整数的包装器),则共享它并没有太多好处。

The best way is to not use a pointer to a Vector3D, but take it by value. If Vector3D is what I suspect (a wrapper around 3 floats or integers), there is not much benefit performance wise to sharing it.

您还可以开始更多地考虑所有权,但要销毁客户端代码上的 Vector3D 的负担(构造 Entity )的代码。

You can also start to reason more about ownership and but the burden of destroying the Vector3D on the client code (the code that constructs an Entity).

如果这不是一个选项,则可以使用 std :: shared_ptr

If this is not an option, you can use a std::shared_ptr.

#include <memory>
struct Vector3D {};

struct Entity {
  // Construct from another shared_ptr.
  Entity(std::shared_ptr<Vector3D> v) : v_(v) {}

  // Assume ownership of `v`.
  Entity(Vector3D* v) : v_(v) {}

  // depending on which guarantees we have for sharing the vector 
  // we can omit checks for null.
  const Vector3D& vector() const { return v_.get(); }
  Vector3D& vector() { return v_.get(); }

private:
  std::shared_ptr<Vector3D> v_;
};

这篇关于C ++对象组合,依赖注入和复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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