1
    #include <iostream>
    #include <new>
    
    const int BUF = 512;
    const int N = 5;
    char buffer[BUF];

    int main(){
        using namespace std;
    

        double *pd1, *pd2;
        int i;
        cout << "Calling new and placement new: \n";
        pd1 = new double[N];
        pd2 = new (buffer) double[N];
        for(i = 0; i < N; i++){
            pd2[i] = pd1[i] = 1000 + 20.0 * i;
        }
        cout << "Memory addresses:\n" << " heap: " << pd1
            << " static: " << (void *)buffer << endl;
        cout << "Memory contents:\n";
        for(i = 0; i < N; i++){
            cout << pd1[i] << " at " << &pd1[i] << "; ";
            cout << pd2[i] << " at " << &pd2[i] << endl;
        }
        delete [] pd1;
        return 0;
}

newplace.cpp:15:32: error: no matching function for call to ‘operator new [](sizetype, char [512])’ pd2 = new (buffer) double[N];

Wolf
  • 9,679
  • 7
  • 62
  • 108
Mr yang
  • 11
  • 1
  • 4
    [Can't reproduce](https://godbolt.org/z/fYG3nY). This program compiles and runs for me. – Igor Tandetnik Jul 22 '20 at 02:16
  • What compiler and version are you using? – Dai Jul 22 '20 at 02:16
  • g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 – Mr yang Jul 22 '20 at 02:45
  • Maybe it's just a matter of the complier, which works in my Visual Studio IDE.Thanks – Mr yang Jul 22 '20 at 02:53
  • Please compile with `g++ -Wall -Wextra -g` and show the *exact* error messages obtained in your question, as an [mre]. See [this C++ reference](https://en.cppreference.com/w/cpp). Explain in your question what forbids you from using standard [C++ containers](https://en.cppreference.com/w/cpp/container). **Read a [good C++ programming book](https://stroustrup.com/programming.html)** – Basile Starynkevitch Jul 22 '20 at 06:07
  • 3
    `pd2 = new (buffer) double[N];` This is [dangerous](https://stackoverflow.com/questions/8720425/array-placement-new-requires-unspecified-overhead-in-the-buffer)! – Evg Jul 22 '20 at 06:07

0 Answers0