簡體   English   中英

unique_ptr 的分段錯誤

[英]Segmentation fault with unique_ptr

我正在嘗試使用 unique_ptr 而不是自己分配 memory 。 我有以下代碼:

class Album {
...
public:
    Add(Song* song);
...
}

void func(){
    ...
    std::unique_ptr<Album> album = std::unique_ptr<Album>{new Album()};
    std::unique_ptr<Song> song = std::unique_ptr<Song>{new Song(soundtrack.data(), soundtrack.length())};
    album->Add(song.get());
    ...
}

我得到線路的分段錯誤:

album->Add(song.get());

我嘗試了多種變體來獲取指針,包括 std::move 和 make_unique,但也許我不明白 unique_ptr 如何很好地解決它。

有任何想法嗎?

問題如下

class Album {
...
public:
    Add(Song* song);
...
}

void func(){
    ...
    std::unique_ptr<Album> album = std::unique_ptr<Album>{new Album()};
    std::unique_ptr<Song> song = std::unique_ptr<Song>{new Song(soundtrack.data(), soundtrack.length())};
    album->Add(song.get());
    ...
    // Here the object song gets destructed. This means that the underlying Song gets destructed.
    // So right after leaving func() the pointer that was returned by song.get() now points to non-allocated memory containing random bits at worst case.
}

所以一種可能的解決方案是......

class Album {
...
public:
    Add(std::unique_ptr<Song>&& song); // you still need to move song inside Add(...)
...
}

void func(){
    ...
    std::unique_ptr<Album> album = std::unique_ptr<Album>{new Album()};
    std::unique_ptr<Song> song = std::unique_ptr<Song>{new Song(soundtrack.data(), soundtrack.length())};
    album->Add(std::move(song)); //here song is intended  to be moved inside Add(...)
    ...
    // If moved inside Add(...) song points to nullptr here.
}

您提供的代碼可以編譯並運行良好-因此您未提供的部分肯定存在問題-我懷疑Add()中的代碼或其返回類型,或者稍后使用指針,因為懷疑是ecktschnagge 工作示例在 gdbonline 上:
https://onlinegdb.com/r1oyXGK2S

by use of std::unique_ptr .首先我問一個問題,通過使用std::unique_ptr獲得什么優勢。 考慮到唯一指針並不能保證有一個指針 - 在Add()內你必須檢查nullptr ,我認為從你的用法來看,你不想使用std::unique_ptr

關鍵是,一個std::unique_ptr只有一個唯一的所有權。 其中之一:

  • func() ::本地 scope
  • album::Add() ::parameter_scope

擁有它。

由於您沒有使用std::move()所有權保留在func()中,並將在 func( func()結束時被銷毀。 為避免這種情況,您不妨使用song.release() (請參閱cpp-reference )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM