我正在用 C++ 为新容器编写迭代器。当我调用 begin() 和 end() 函数(都非常短)时,我希望编译器将其内联。但它没有。我想可能是因为迭代器作为临时对象返回,需要复制。我想也许我可以在 c++11 中使用 RValue 引用,但我不熟悉它。那么有没有办法让它内嵌呢?
代码是这样的(不完全一样,但我想如果这个版本能用,我的代码也能用)。
我使用的是 VC++ 2013 CTP,我已经更改了编译选项,但它也不起作用。
class Pointer
{
public:
Pointer(int* p) : p(p)
{
(*p)++;
}
Pointer(const Pointer& pointer) : p(pointer.p)
{
(*p)++;
}
Pointer& operator =(const Pointer& pointer)
{
(*p)--;
p = pointer.p;
(*p)++;
}
int* p;
~Pointer()
{
(*p)--;
}
static Pointer create(int& p)
{
return Pointer(&p);
}
static Pointer create2(int& p)
{
return create(p);
}
};
int main()
{
int p = 0;
Pointer pointer = Pointer::create2(p);
}
这里的函数 create 和 create2 不是内联的,即使你可以看到,它真的很简单。
我知道这可能不会影响我的程序速度,但我只是想让它变得更好。
最佳答案
有几种情况微软的编译器不能内联函数:
http://msdn.microsoft.com/en-us/library/a98sb923.aspx
In some cases, the compiler will not inline a particular function for mechanical reasons. For example, the compiler will not inline:
A function if it would result in mixing both SEH and C++ EH.
Some functions with copy constructed objects passed by value when -GX/EHs/EHa is on.
Functions returning an unwindable object by value when -GX/EHs/EHa is on.
Functions with inline assembly when compiling without -Og/Ox/O1/O2.
Functions with a variable argument list.
A function with a try (C++ exception handling) statement.
因为函数按值返回 Pointer
并且它有一个析构函数,所以函数不能内联。
除了更改 Pointer 类之外,没有什么可以真正解决的。右值引用在这里没有帮助。我会保留代码原样,如果您需要在最终产品中获得更好的性能,请尝试使用其他编译器。
RVO 可能会在这里发生,但不会有什么不同,因为复制的成本非常小。
关于c++ - 使函数返回内联临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577214/