Skip to content

Instantly share code, notes, and snippets.

@dwilliamson
Created August 22, 2017 22:17
Show Gist options
  • Save dwilliamson/6991d6bdf401d273b677105ab0064ea1 to your computer and use it in GitHub Desktop.
Save dwilliamson/6991d6bdf401d273b677105ab0064ea1 to your computer and use it in GitHub Desktop.
MSVC (multiple versions past) can NRVO this copy out of existence
#include <stdio.h>
#include <stdint.h>
#include <cstdlib>
// Dumbest array type possible with lots of copying and rubbish code
// Note absence of generated copy constructor calls for the array or its items
template <typename Type>
struct Array
{
Array()
{
}
Array(const Array& rhs)
: size(rhs.size)
{
items = new Type[size];
for (int i = 0; i < size; i++)
items[i] = rhs.items[i];
}
Array& operator= (const Array& rhs)
{
size = rhs.size;
items = new Type[size];
for (int i = 0; i < size; i++)
items[i] = rhs.items[i];
return *this;
}
void resize(int size_)
{
size = size_;
items = new Type[size];
}
Type* items = nullptr;
int size = 0;
};
struct Obj
{
Obj()
{
printf("construct\n");
}
Obj(const Obj&)
{
printf("copy construct\n");
}
~Obj()
{
printf("destruct\n");
}
};
_declspec(noinline) Array<Obj> Apply(int v)
{
Array<Obj> r;
r.resize(rand()%v);
return r;
}
int main()
{
Array<Obj> x = Apply(7);
for (int i = 0; i < x.size; i++)
printf("%x", &x.items[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment