3

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?

Aristotle0
  • 317
  • 2
  • 9
  • A `std::string` will allocate the memory it needs to store the value. And release it when done. You don't have to do anything. – Bo Persson Aug 13 '16 at 09:36
  • When you create the object whether it be on the stack or heap, as Bo Persson said the constructor for string allocates memory for the string object, whatever way you provide initialization for your string whether through default initialization or providing the string. If you change the value later memory will be reallocated. Whether you care about the issue of reallocation is up to you.Someone please correct me if I'm wrong. – TimLayne Aug 13 '16 at 20:14
  • You did provide a constructor and no default constructor for your Pimpl struct so you will need to provide that value for it to be allocated. – TimLayne Aug 13 '16 at 20:17

2 Answers2

1

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

Torbjörn
  • 5,512
  • 7
  • 46
  • 73
  • if somebody is interested in memory consumption, allocation etc, memory usage is higher than core class object. But maybe this knowledge isn't required in every situation – Jacek Cz Aug 13 '16 at 10:05
0

Torbjorn's answer is great. I'm just to add some extra points.

The string class itself must have some certain value in size that you can get it from sizeof. That's what you actually store in your own class. Then for the data stored in the string, it is derived from and managed by the string object (It should typically be some pointer (which may be the start point of your string) but I'm unsure about it). So you don't have to worry about it, the standard library has already wrapped it for you.

YiFei
  • 1,752
  • 1
  • 18
  • 33