类模板中的性能

performance in class template

本文关键字:性能      更新时间:2023-10-16

我的类模板如下

template<class T>
class A
{
public:
    A(T t) : m_t(move(t)) {}
    operator T const&() const { return m_t; }        
private:
    T m_t;
};

Tint

(1)构造函数中的move是否具有性能下降而没有移动?

(2)operator T const&()是否具有与operator T&()相比的性能下降?

  1. 复制和移动和int是相同的

考虑:

struct A {
   int A;
};
struct B {
   std::string str;
};

对于a,复制和移动是相同的(复制嵌入的int)。对于B,复制是为字符串分配内存(通常)。但是,移动将只是复制指向从字符串,O(1)操作以及可能的大小的指向堆分配的内存的指针。字符串具有远程零件,因此,仅移动指针时。

  1. 编译器非常擅长优化,我相信它将为INT生成相同的代码,因为INT不是多态或可衍生的(类)。