gpt4 book ai didi

c++ - 创建一个指向包含字符串的新类的指针

转载 作者:太空狗 更新时间:2023-10-29 22:58:53 25 4
gpt4 key购买 nike

我认为new 或智能指针需要内存大小。如果一个类包含字符串,我分配这个类。然后我给字符串赋一个新值,是不是超过了内存?

// a.hpp
#include <string>
#include <memory>
#include <armadillo>

class A {
public:
A(const std::string &);
private:
struct Impl;
std::shared_ptr<Impl> impl;
};

// a.cc
struct A::Impl {
Impl(const std::string &f)
{
// read config file and get name and size of x
name = "abc";
x.zeros(2, 3);
}

std::string name;
arma::mat x;
};

A::A(const std::string &f):
impl(std::make_shared<Impl>(f)) {}

对于这个例子,我想我只分配了N内存,但是我使用了N+M内存。危险吗?

最佳答案

std::string 的赋值运算符将处理所有需要的内存分配。您无需担心这一点。

关于c++ - 创建一个指向包含字符串的新类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com