【问题标题】:How to save a string to a string* member of a class in C++?如何将字符串保存到 C++ 中类的 string* 成员?
【发布时间】:2020-03-20 19:41:28
【问题描述】:

我有一个 C++ 类,它的成员中包含 std::string*。我想为这个类创建一个构造函数,它以std::string 作为参数并使字符串指针指向它:

class foo
{
private:
    std::string * bar;
public:
    foo(std::string);
}
foo::foo(std::string s)
{
    //code
}

如果我这样做 this->bar = &s; 它显然不起作用(保存 s 字符串的地址,因为它应该)。我该怎么做?

我尝试创建一个以字符串指针作为参数的构造函数,但它也无法正常工作,我假设出于类似的原因。

编辑:在阅读 cmets 后,我决定更改构造函数,因此它现在将 std::string* 作为其参数,并从那里开始工作。

【问题讨论】:

  • 为什么它包含 std::string* ?这是非常不寻常的。你不能改变这个糟糕的设计吗?
  • 您需要创建一个指针并为其在构造函​​数中指向的对象赋值。话虽如此,您应该避免输入 std::string* 并改用 std::string
  • 然后将您的构造函数更改为:foo::foo(std::string* s) 尽管在这种情况下您可能希望使用 std::shared_ptr<:string> 和 std::weak_ptr<:string>
  • 体内不需要任何东西。只需使用成员明智的初始化:foo::foo(std::string* s) : bar{s} {}
  • 出于同样的原因,类需要指向字符串(或引用)的指针,类的构造函数也需要指向字符串(或引用)的指针。没有一个论点不适用于另一个。

标签: c++ string pointers constructor


【解决方案1】:

你可以这样写你的构造函数:

foo::foo(std::string s)
{
    bar = new std::string(s);  // code
}

但是现在你有内存泄漏,所以你需要一个析构函数:

foo::~foo() { delete bar; }

然后您需要实施或禁用复制/分配。

class foo final
{
   ...
   foo(const foo&) = delete;
   foo& operator=(const foo&) = delete;
   ...
 };

存储指向std::string 的指针而不是实例需要付出很多努力:

class foo final
{
    std::string bar;  // NOT std::string* bar
public:
    foo(std::string s) : bar(s) {}
};

如果你真的想要一个指针,使用std::unique_ptrstd::shared_ptr 会更好。

class foo final
{
    std::unique_ptr<std::string> bar;
public:
    foo(std::string s) : bar(std::make_unique<std::string>(s)) {}
};

std::unique_ptr 无法复制/分配,因此您甚至不必禁用 foo 的复制/分配,尽管您可能希望获得更好的错误消息。

【讨论】:

  • 在此处添加有关Rule of Zero 的注释,因为这是您应该争取的。不存在的代码没有错误。
【解决方案2】:

如果绝对需要有一个指向字符串的指针 - 确保获得该字符串的所有权(例如,首先制作它的内部副本)。比使用该副本的地址初始化您的指针。

class foo
{
private:
    std::string * bar;
    std::string redundantCopyOfTheString;
public:
    foo(std::string);
}
foo::foo(std::string s):
   redundantCopyOfTheString(s),
   bar(&redundantCopyOfTheString)
{
    //code
}

但是,首先要确保你确实需要这个指针作为类的成员。它看起来像一个糟糕的设计。

我建议您描述一个导致您使用这种基于指针的解决方案的问题,并将其作为一个单独的问题发布,并请求改进设计。

【讨论】:

  • @OpalApps 恐怕我不能同时拥有字符串和字符串指针,我会让用户仅使用字符串来复制信息,但我不能,我需要指针使其指向独特的信息(我正在争取最少的数据重复)
  • @Zap 这就是答案的重点,建议您重新考虑您的方法。请打开一个新问题,描述您的问题并寻求架构建议,而不是专注于如何在您的类中初始化指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 2022-01-25
  • 1970-01-01
  • 2015-10-05
相关资源
最近更新 更多