Search code examples
c++vectormove

Can a temporary object be passed by value without destroying the original in C++


In the following code, the pointer is reset when a struct S is destructed. I'd prefer a vector of structure values instead of pointers. Is there a way to add to the vector without the temporary getting destructed?

int* pi = nullptr;

struct S
{
    S(int* i) { pi = i; }
    ~S() { pi = nullptr; }
};

int main(int argc, char* args[])
{
    int i = 5;
    std::vector<S> sVector;
    sVector.push_back(S(&i));
    std::cout << pi << std::endl; // outputs 0 instead of address
    return 0;
}

Solution

  • You're looking for emplace_back:

    sVector.emplace_back(&i);
    

    That will construct an S in-place, no temporaries anywhere.

    Note, however, that you have no guarantee that an append operation won't trigger a resize - and a resize would involve copying and destroying a bunch of Ss.