In general, everything works as I had in mind. Ignore the presence of setlocale in all functions. The problem is that I do not understand why the copy constructor is not called when the operator function is called. Maybe a stupid question, I only do 20 days from the power of PS environment code blocks

#include <iostream> #include <cstring> #include <cstdio> #include <windows.h> using namespace std; class cl { char* p; public: cl take(); void output(){cout<<p;} void operator=(cl ob); void strcp(char* str); cl(char* str); cl(const cl& ob); ~cl(){delete p;cout<<"\nОбъект удален\n";} }; cl cl::take() { setlocale(LC_ALL,"Russian"); cl ob2(p); strcpy(ob2.p,p); p = 0; return ob2; } cl::cl(const cl& ob) { setlocale(LC_ALL,"Russian"); p = new char [strlen(ob.p)]; cout<<"\nКопия объекта создана!\n"; } void cl::operator=(cl ob) { p = new char [strlen(ob.p) + 1]; strcpy(p,ob.p); } cl::cl(char* str) { setlocale(LC_ALL,"Russian"); p = new char [strlen(str) + 1]; cout<<"\nОбъект создан!\n"; } inline void cl::strcp(char* str) { strcpy(p,str); } int main() { int len; setlocale(LC_ALL,"Russian"); cout<<"Введите длину строки:\n"; cin>>len; char str[len]; while(cin.get() != '\n') { cin.clear(); } cout<<"Введите строку:\n"; gets(str); cout<<'\n'<<strlen(str)<<'\n'; OemToCharA(str,str); cl ob(str); ob.strcp(str); ob = ob.take(); cout<<"\nТут должен быть конструктор копии\n"; ob.output(); } 

    1 answer 1

    Let's start with the fact that you shouldn’t compile it - according to the standard:

     char str[len]; 

    len must be a constant, not a variable. gets forget right away like a nightmare! Categorically!

    setlocale enough to call once, and not before each output. Well, you wrote it yourself ...

    And the last thing - turn off all optimization, and you will have to see a call to the copy constructor. Simply, the optimizer is smart enough, realizes that you can do without a constructor, creating the returned object directly in a variable, without copying (so-called RVO optimization, the standard is allowed).

    At least, VC ++ with /Od does call the copy constructor ...

    • there are a lot of things strangely done, but as I understand it, this is an academic example .... - Andrey Golikov
    • In this case, it will be NRVO - yrHeTaTeJlb