[ create a new paste ] login | about

Link: http://codepad.org/NwZPEWyx    [ raw code | output | fork ]

fisherro - C++, pasted on Feb 3:
#include <string>
#include <cctype>
#include <algorithm>
#include <functional>
#include <iostream>
#include <cstdlib>
#include <cstdio>

void* operator new(std::size_t size) throw(std::bad_alloc)
{
    //std::cout << "New size=" << size << std::endl;
    //Avoid code that might call new/delete!
    std::printf("New size=%lu\n", static_cast<unsigned long>(size));
    return std::malloc(size);
}

void operator delete(void* p) throw() //noexcept
{
    //std::cout << "Delete" << std::endl;
    std::puts("Delete");
    std::free(p);
}
 
int main()
{
    //Transform a string in-place
    std::string s("hello");
    std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
    std::cout << s << std::endl;

    //Transform a string while copying
    std::string s2;
    s2.reserve(s.size());
    std::transform(s.begin(), s.end(), std::back_inserter(s2), std::ptr_fun<int, int>(std::tolower));
    std::cout << s2 << std::endl;

    //Does this cause more memory allocations?
    //Yes. In one test it took 4 allocations instead of just one above.
    std::string s3;
    std::transform(s.begin(), s.end(), std::back_inserter(s3), std::ptr_fun<int, int>(std::tolower));
    std::cout << s3 << std::endl;
}


Output:
New size=8
New size=20
New size=112
New size=112
New size=48
New size=2
Delete
New size=8
New size=20
New size=112
New size=112
New size=48
New size=2
Delete
New size=18
HELLO
New size=18
hello
New size=14
New size=15
Delete
New size=17
Delete
New size=21
Delete
hello
Delete
Delete
Delete


Create a new paste based on this one


Comments: