【问题标题】:C++ Templates: Do they create a new object and destoy them at the end of the function / method?C++ 模板:它们是否创建一个新对象并在函数/方法结束时销毁它们?
【发布时间】:2020-12-29 19:33:26
【问题描述】:

我正在尝试编写一个通用模板方法,该方法使用具有所需成员的对象将一个简单的 Rectangle 呈现到屏幕上。但是,我注意到析构函数不断被调用。现在,这不是什么大问题,但对于我想到的其他模板,它会(例如纹理)。

那么模板是否总是创建作为参数传递的对象的副本?

template<typename T>
    void renderRect(T thisObject, int red, int green, int blue, int alpha)
    {
        SDL_Rect object = { thisObject.x, thisObject.y, thisObject.w, thisObject.h };

        SDL_SetRenderDrawColor(this->renderer, red, green, blue, alpha);
        SDL_RenderFillRect(this->renderer, &object);
    }

【问题讨论】:

  • 这与模板无关。 thisObject 按值传递,因此被复制。
  • 大声笑,我是 cpp 的新手。但我明白,这太基本了(愚蠢):) 感谢您的快速响应:)

标签: c++ object templates


【解决方案1】:

如果T 是一个对象类型(例如classstruct),那么T thisObject 确实需要一个值副本。

你想要void renderRect(const T&amp; thisObject, int red, int green, int blue, int alpha)吗?

【讨论】:

  • 是的,这是我第一次尝试模板,我什至从来没有想过我需要通过引用传递它(我说得对吗?)。但现在很明显。非常感谢:)
  • @Lyingdutchman 哦,这是一个阴暗的世界:整本书都致力于这个主题。个人最爱:amazon.co.uk/Templates-Complete-Guide-David-Vandevoorde/dp/…(主要作者是荷兰同胞!)。
  • 非常感谢,一定会调查的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
相关资源
最近更新 更多