Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a pointer to new class which contains string

I think new or smart pointer needs the size of memory. If a class contains string, I allocate the class. Then I assign a new value to the string, is it over the memory?

// 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)) {}

For this example, I think I only allocate N memory, but I use N+M memory. Is it dangerous?

like image 243
Aristotle0 Avatar asked Feb 14 '26 10:02

Aristotle0


1 Answers

The assignment operator of std::string will take care of all the required memory allocation. You don't need to worry about that point.

like image 106
Torbjörn Avatar answered Feb 16 '26 23:02

Torbjörn