Search code examples
c++c++11visual-studio-2013inline

Make a function returning temporary object inline?


I'm writing an iterator for a new container in c++. When I call begin() and end() functions (both very short), I expected the compiler to make it inline. But it didn't. I think maybe it's because the iterator is returned as a temporary object, and it needs to be copied. I think maybe I can use the RValue reference in c++11, but I'm not familiar with it. So is there a way to make it inline?

The code is something like this (not exactly the same, but I think if this version works, my code will also work)。

I'm using VC++ 2013 CTP, and I have changed compile options but it doesn't work either.

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);
}

The function create and create2 here are not inline even if, you can see, it's really simple.

I know maybe this doesn't make a difference in the speed of my program, but I just want to have it better.


Solution

  • There are several cases where microsoft's compiler cannot inline functions:

    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.

    Because the functions return Pointer by value and it has a destructor, the functions cannot be inlined.

    There's nothing that can really be done about it other than changing the Pointer class. Rvalue refs don't help here. I would just leave the code as it is and if you need better performance in final product, try another compiler.

    RVO may happen here but it doesn't make difference because the cost of copying is so small.