「C++の基礎 - スマートポインタ(unique ptr)」の版間の差分

📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

 
219行目: 219行目:
<code>std::vector</code>クラスを使用する方法は、より柔軟性が高く、一般的に推奨される。<br>
<code>std::vector</code>クラスを使用する方法は、より柔軟性が高く、一般的に推奨される。<br>
一方で、<code>std::unique_ptr</code>クラスを使用する方法は、パフォーマンスが重要で、配列サイズが固定の場合に適している。<br>
一方で、<code>std::unique_ptr</code>クラスを使用する方法は、パフォーマンスが重要で、配列サイズが固定の場合に適している。<br>
<br>
==== 例 : Linuxのグループの取得 ====
<syntaxhighlight lang="c++">
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#include <memory>
#include <grp.h>
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
std::vector<std::string> getUserGroups(std::string& errorMessage)
{
    std::vector<std::string> groups;
    errorMessage.clear();
    uid_t uid = getuid();
    struct passwd *pw = getpwuid(uid);
    if (!pw) {
      std::stringstream ss;
      ss << "Failed to get user info: " << strerror(errno);
      errorMessage = ss.str();
      return groups;
    }
    int ngroups = 0;
    if (getgrouplist(pw->pw_name, pw->pw_gid, nullptr, &ngroups) == -1) {
      errorMessage = "Failed to get group list size";
      return groups;
    }
    if (ngroups > 0) {
      auto gids = std::make_unique<gid_t[]>(ngroups);
      if (getgrouplist(pw->pw_name, pw->pw_gid, gids.get(), &ngroups) == -1) {
          errorMessage = "Failed to get group list";
          return groups;
      }
      for (int i = 0; i < ngroups; i++) {
          errno = 0;
          struct group *gr = getgrgid(gids[i]);
          if (gr) {
            groups.push_back(gr->gr_name);
          }
          else {
            std::cerr << "Failed to get group name for gid " << gids[i] << ": " << strerror(errno) << std::endl;
          }
      }
    }
    else {
      errorMessage = "User is not a member of any groups";
    }
    return groups;
}
</syntaxhighlight>
<br><br>
<br><br>