Accessing placement new buffer



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <cstdlib>
#include <iostream>

using namespace std;




class Obj{
      
      
      public:
      Obj(){cout<<"Obj1 has been created"<<endl;}
      ~Obj(){cout<<"Obj1 has been destroyed"<<endl;}
      void sayname(){ cout<<"hello"<<endl; }
      };



char * buffers[10];
Obj * objects[10];

int main(int argc, char *argv[])
{
    
   buffers[1] = new char[sizeof(Obj)];
objects[1] = new(buffers[1]) Obj();

cout<<buffers[1]<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}



Hello, how come i get garbage value whenever i try printing the buffers[1]?

Last edited on
Firstly, you aren't initialising any of the values of the buffers. Secondly don't use naked news, more often than not you'll end up with either really long, hateful code or memory leaks. Use RAII (google it). Also, why initialise buffers[1] not buffers[0]?
oops nvm i fixed it.

although i have a solution, can anyone show me a proper initialization of buffers?
Last edited on
This entirely depends on how what exactly you're trying to do. For example pointers to arrays is very weird, so either you'd use a string, or a vector. But for initialising buffer (not sure what you're doing with object) you should do something like this:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <memory>
#include <string>

int main()
{
  std::unique_ptr<std::string> buffer (new std::string);
  *buffer = "Whatever you want it to";
  std::cout<<buffer[0]<<std::endl;
  return 0;
}
Topic archived. No new replies allowed.