Skip to content

Instantly share code, notes, and snippets.

@MarekKnapek
Last active May 28, 2021 15:37
Show Gist options
  • Save MarekKnapek/4a593e6589b8f3ca65b15005ca5636a3 to your computer and use it in GitHub Desktop.
Save MarekKnapek/4a593e6589b8f3ca65b15005ca5636a3 to your computer and use it in GitHub Desktop.
const vs non-const in post increment operator
#define WANT_CONST 1
#include <cstdio>
class my_type
{
public:
my_type() noexcept;
my_type(my_type const& other);
my_type(my_type&& other) noexcept;
my_type& operator=(my_type const& other);
my_type& operator=(my_type&& other) noexcept;
~my_type() noexcept;
public:
my_type& operator++();
my_type operator++(int);
};
my_type::my_type() noexcept
{
std::printf("default ctor %p\n", this);
}
my_type::my_type(my_type const& other)
{
std::printf("copy c-tor %p %p\n", this, &other);
}
my_type::my_type(my_type&& other) noexcept
{
std::printf("move c-tor %p %p\n", this, &other);
}
my_type& my_type::operator=(my_type const& other)
{
std::printf("copy assign %p %p\n", this, &other);
return *this;
}
my_type& my_type::operator=(my_type&& other) noexcept
{
std::printf("move assign %p %p\n", this, &other);
return *this;
}
my_type::~my_type() noexcept
{
std::printf("d-tor ctor %p\n", this);
}
my_type& my_type::operator++()
{
std::printf("pre-increment %p\n", this);
return *this;
}
my_type my_type::operator++(int)
{
std::printf("post-increment %p\n", this);
#if WANT_CONST == 0
my_type copy = *this;
#elif WANT_CONST == 1
my_type const copy = *this;
#endif
operator++();
return copy;
}
int main()
{
my_type my_object;
my_type copy = my_object++;
}
// Compile by Visual Studio 2019 and run.
// cl test.cpp && test
//
// default ctor 007FF82F
// post-increment 007FF82F
// copy c-tor 007FF81B 007FF82F
// pre-increment 007FF82F
// copy c-tor 007FF82E 007FF81B // <== This is the copy I was talking about.
// d-tor ctor 007FF81B
// d-tor ctor 007FF82E
// d-tor ctor 007FF82F
//
//
// Now compile with optimizations.
// cl /O2 test.cpp && test
//
// default ctor 003BFE3E
// post-increment 003BFE3E
// copy c-tor 003BFE3F 003BFE3E
// pre-increment 003BFE3E // <== There is no copy nor move constructor between those two lines.
// d-tor ctor 003BFE3F // <== This is what you were talking about.
// d-tor ctor 003BFE3E
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment