Strange segfault with unique_ptr and shared_ptr

I went through a weird segfault. The reason actually led me to an error, but I still don't understand why the segmentation error occurs here ... Code:

#include <memory>
int main(int argc, char **arv)
{
    int *i = new int;
    std::unique_ptr<int> u1(i);
    std::unique_ptr<int> u2;
    u1 = std::move(u2); // line 7
    std::shared_ptr<int> s1(i); // line 8
    std::shared_ptr<int> s2;
    s2 = s1;
}

I compile with g ++ 4.6 -std=c++0xand get segfault.

If I change line 7 to u2 = std::move(u1);(it was an error), it disappears. If I change line 8 to std::shared_ptr<int> s1(new int(3));(which of course I don't want), it will also disappear. If I remove from line 8 there is also no segfault.

, , segfault. ,
7 u1. reset(), . i . ? , , !

? ?

, Steffen

+3
2

8 : i unique_ptr, , ! *i, .

:

std::shared_ptr<int> s1(std::move(u2));

( , u1 u2 .)

+11

:

u1 = std::move(u2);

, u1. i . shared_ptr, free'd, - undefined.

+3

All Articles