通过构造函数在 cpp 文件中设置时访问在 hpp 文件中声明的 c++ 唯一指针

accessing a c++ unique pointer declared in hpp file when set in a cpp file through constructor

我是一名 C++ 初学者,我对如何从 class 构造函数设置私有唯一值同时仍然设法从其他 public 函数访问它感到有点困惑。我什至应该使用唯一指针开头还是共享指针?

示例:(来自我正在处理的项目)

header.hpp

class PixelHandler {
private:
// don't know if this ia legal
 std::unique_ptr<Ppm> ppm;
 std::vector<std::vector<int>> coordList;
 std::unordered_map<std::string, std::string> generatePassList(std::unordered_map<int, int>);
 

public:
 PixelHandler(int sizex, int sizey);
 PixelHandler(std::string picture);
 std::unordered_map<std::string, std::string> retrievePasswordList();
 void setPasswordList(std::string key, std::string password);

};

source.cpp

PixelHandler::PixelHandler(std::string picture)
{
  
   ppm = Ppm(picture.substr(0, -4) + ".ppm");

}

也许你应该这样做:

ppm = std::make_unique<Ppm>(picture.substr(0, -4) + ".ppm");

因为您无法将对象(Ppm 类型)分配给指针。您需要将它传递给 std::unique_ptr 的构造函数,以便它可以创建一个指向该对象的唯一指针。

Should I even be using a unique pointer to begin with or a shared pointer instead?

如果您不知道指针的用途,则无法告知您这一点。 PixelHandler 会是唯一 class 访问 ppm 吗?即使您从 PixelHandler 内的不同点访问它,那些其他访问将如何?例如,其他访问者接收指向 ppm 的原始指针是否足够(例如 Ppm 上的只读操作)?...使用 unique_ptrshared_ptr 主要与您指向的对象的所有权有关。

I'm a c++ beginner and am a little confused about how I would set a private unique from a class constructor while still managing to access it from other public functions.

您可以在 PixelHandler 的构造函数中初始化 Ppm 指针,然后从其他 PixelHandler 的方法中使用它。在 PixelHandler 实例被销毁之前,Ppm 实例不会被销毁。

顺便说一句,如果您想从图片路径(例如 jpgpng 等)形成 Ppm 路径,您可以使用 std::filesystempathreplace_extension)。我不认为 substr(0, -4) 在 C++ 中可以作为删除扩展名的方法。

[Demo]

#include <filesystem>
#include <iostream>  // cout
#include <memory>  // make_unique, unique_ptr
#include <string>

class Ppm
{
    const std::string file_extension{"ppm"};
public:
    Ppm(std::filesystem::path path)
    : path_{path.replace_extension(file_extension)}
    {
        
        std::cout << "Ppm ctor: " << path_ << "\n";
    }
    ~Ppm() { std::cout << "Ppm dtor\n"; }
private:
    std::filesystem::path path_{};
};

class PixelHandler
{
public:
    PixelHandler(std::filesystem::path path)
    : ppm_up_{std::make_unique<Ppm>(std::move(path))}
    {}
    ~PixelHandler() { std::cout << "PixelHandler dtor\n"; }
private:
    std::unique_ptr<Ppm> ppm_up_{};
};

int main()
{
    PixelHandler ph("blah.jpg");
    std::cout << "\n... short life :(\n\n";
}