Zap*_*Zap 3 c++ string constructor pointers
我有一个 C++ 类,它的成员中包含一个std::string*. 我想为这个类创建一个构造函数,它将 astd::string作为参数并使字符串指针指向它:
class foo
{
private:
std::string * bar;
public:
foo(std::string);
}
foo::foo(std::string s)
{
//code
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做this->bar = &s;显然不起作用(保存 s 字符串的地址,因为它应该)。我该怎么做?
我尝试创建一个以字符串指针作为参数的构造函数,但它也无法正常工作,我假设出于类似的原因。
编辑:阅读评论后,我决定更改构造函数,因此现在将 astd::string*作为其论证,并从那里开始工作。
您可以按如下方式编写构造函数:
foo::foo(std::string s)
{
bar = new std::string(s); // code
}
Run Code Online (Sandbox Code Playgroud)
但是现在你有内存泄漏,所以你需要一个析构函数:
foo::~foo() { delete bar; }
Run Code Online (Sandbox Code Playgroud)
然后您需要实现或禁用复制/分配。
class foo final
{
...
foo(const foo&) = delete;
foo& operator=(const foo&) = delete;
...
};
Run Code Online (Sandbox Code Playgroud)
存储指向std::string而不是实例的指针需要付出很多努力:
class foo final
{
std::string bar; // NOT std::string* bar
public:
foo(std::string s) : bar(s) {}
};
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一个指针,这将是很多更好地使用std::unique_ptr或std::shared_ptr。
class foo final
{
std::unique_ptr<std::string> bar;
public:
foo(std::string s) : bar(std::make_unique<std::string>(s)) {}
};
Run Code Online (Sandbox Code Playgroud)
std::unique_ptr不能被复制/分配,所以你甚至不必禁用复制/分配foo,尽管你可能想要更好的错误消息。