Did I guarantee one pair of constructor and destructor calls when returning an object initialized with a copied initialization list?

Take the following class, for example

#include <iostream>

using namespace std;

class A{
private:
    int a_;
    int b_;

    A(const A&) = delete;
    A& operator=(const A&) = delete;
    A(A&&) = delete;
    A& operator=(A&&) = delete;

public:
    A(int a, int b) : a_{a}, b_{b}{cout<<"constructed\n";}

    void ephemeral() const{cout<<"operation\n";}

    ~A(){cout<<"destructed\n";}

};

A make_A(int a, int b){
    return {a, b};
}

int main(){
    make_A(1, 2).ephemeral();
    return 0;
}

It gives the expected result .

The object is built, the operation is performed, and then destroyed.

However, I am concerned about whether this is guaranteed. My main problem is whether I can see any effects that I don’t know about, due to the freedom the compiler has with the standard.

I don’t think copy-elision is a factor here because all move and copy constructors are declared deleted, so how can they be called?

- , . , , ?

, "", .

+4
1

return {a,b};, .

, . .

main. .ephemeral(). , "" A const& ( ) A&& ( ), auto const& auto&& :

auto&& a = make_A(1, 2);
a.ephemeral();

, .

.

, . Elision - . , make_A :

A make_A(int a, int b){
  A r{a,b};
  return r;
}

r . , , A(A const&) A(A&&), A. , , , , r make_A , make_A.

,

A a = make_A(1,2);

, make_A, , A. Elision , make_A. A(A&&) A(A const&).

/, , . ( ).

, .


++ 17 return A(a,b); .

A a = make_A(1,2); .

" elision", " , - ".

, , , ctors ++ 03 ++ 11 ++ 14, ++ 17 - "elision" ctors.

+5

Source: https://habr.com/ru/post/1656850/


All Articles