1

Some example program: The problematic line is commented.

#include <iostream>
using namespace std;
class B
{
        static int count;
        int data; 
        int id;
void print(const char* p)
{
        cout <<p <<", "<<id <<", " << data << endl;
}
public:
B(int d=0)
{
        data=d; id=++count; print("B(int)");
}
B(const B& a)
{
        data=a.data; id=++count; print("B(cost B&)");
}
~B()
{
        print("~B()");
}
operator bool()
{
print("bool()"); return (bool)data;
}
B operator+(int i)
{
        print("operator+"); return B(data+i);
}
};
int B::count=0;
void main()
{
B b(42);
B x=b+2;         //             <<<=== HERE IS THE PROBLEM
bool z=b+1;
}

The problem appears after exiting the overloaded '+' function. B x=b+2; // <<<=== HERE IS THE PROBLEM Any suggestions? Thanks

  • What's the exact, unsimplified error? Also, use `int main`. – chris Jun 29 '14 at 13:06
  • 3
    Perhaps you could tell us what the problem is? The code compiles and runs (once I fix the return type of `int main()`); what output do you get, and how does that differ from what you expect? – Mike Seymour Jun 29 '14 at 13:07
  • I expect that the mentioned line will start the copy constructor before moving to the next line. I cant understand why the CC wont start... – user3787714 Jun 29 '14 at 13:10
  • @user3787714, Copies can be elided. – chris Jun 29 '14 at 13:11
  • That's an optimisation known as [*copy elision*](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization). – Mike Seymour Jun 29 '14 at 13:12
  • Thank you! I assume that there is no particular way to know for sure whether the elision will happen or not? – user3787714 Jun 29 '14 at 13:17

0 Answers0