std::allocator <memory>

This is a discussion on std::allocator <memory> within the C++ Programming forums, part of the General Programming Boards category; Not understanding this. Code: std::allocator<string> alloc; auto const p = alloc.allocate(10); Results in p have a <Bad Ptr> upon inspection. ...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    178

    std::allocator <memory>

    Not understanding this.

    Code:
    std::allocator<string> alloc;
    auto const p = alloc.allocate(10);
    Results in p have a <Bad Ptr> upon inspection.

    Code:
    std::allocator<string*> alloc;
    auto const p = alloc.allocate(10);
    This is fine. Why is that as well as for integral types like int? C++ Primer has a clear example using a std::string for the templated type of allocator .

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,752
    Because allocate is enough for plain old data. You want allocator::construct - C++ Reference

    Here's a basic example btw:
    Code:
    #include <memory>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
    
        allocator<string> alloc;
        string* p = alloc.allocate(sizeof *p);
        alloc.construct(p, "hello, world");
    
        cout << *p << endl;
    
        alloc.destroy(p);
        alloc.deallocate(p, 1UL);
    
    }
    Last edited by whiteflags; 02-08-2013 at 04:05 PM.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    178
    Quote Originally Posted by whiteflags View Post
    Because allocate is enough for plain old data. You want allocator::construct - C++ Reference

    Here's a basic example btw:
    Code:
    #include <memory>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
    
        allocator<string> alloc;
        string* p = alloc.allocate(sizeof *p);
        alloc.construct(p, "hello, world");
    
        cout << *p << endl;
    
        alloc.destroy(p);
        alloc.deallocate(p, 1UL);
    
    }

    So my problem was only allocating and not simultaneously constructing the memory leading to <Bad Ptr>. Ok thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocator
    By darren78 in forum C++ Programming
    Replies: 2
    Last Post: 09-07-2010, 08:57 AM
  2. Easy safe memory allocator class/functions
    By jeffcobb in forum C++ Programming
    Replies: 4
    Last Post: 05-30-2010, 03:50 AM
  3. allocator::destroy
    By dra in forum C++ Programming
    Replies: 8
    Last Post: 03-03-2008, 11:33 AM
  4. allocator implementation
    By George2 in forum C++ Programming
    Replies: 4
    Last Post: 02-28-2008, 05:39 AM
  5. Allocator
    By Scarvenger in forum C++ Programming
    Replies: 2
    Last Post: 01-08-2008, 10:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21