c++ copy elision

注意
本文最后更新于 2024-01-12,文中内容可能已过时。

C++ 提供了小对象的 RVO(返回值优化),实现了在函数返回中调用构造函数的功能。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <string>
#include <vector>

class BigObject {
public:
    BigObject() : person_names_(std::vector<std::string>(1000000)) {
        std::cout << "constructor. " << person_names_.size() << std::endl;
    }
    ~BigObject() {
        std::cout << "destructor. " << std::endl;
    }
    BigObject(const BigObject& other) {
        person_names_ = other.person_names_;
        std::cout << "copy constructor. " << person_names_.size() << std::endl;
    }

private:
    std::vector<std::string> person_names_;
};

BigObject Foo() {
    BigObject local_obj;
    return local_obj;
    // return std::move(local_obj);
}

int n {0};

struct C
{
    explicit C(int) {}
    C(const C&) { ++n; }
    int x {1};
};

int main() {
    {
        BigObject obj = Foo();
    }
    //-----Foo()
    //       : BigObject local_obj  -> ctor + copy ctor
    //       : return local_obj     -> dtor
    //BigObject obj
    //       :                      -> copy ctor
    //                              -> dtor
    //       :                      -> dtor

    C c1(42);
    // copy ctor is equivalent to direct-ctor
    C c2 = C(42);
    std::cout << "n:" << n << std::endl;
    return 0;
}

/*
g++ -g -fno-elide-constructors -Wall -std=c++11 main.cpp
main.cpp: In function ‘int main()’:
main.cpp:49:7: warning: variable ‘c2’ set but not used [-Wunused-but-set-variable]
   49 |     C c2 = C(42);
      |       ^~

./a.out
constructor. 1000000
copy constructor. 1000000
destructor.
copy constructor. 1000000
destructor.
destructor.
n:1
*/

/*
g++ -g main.cpp
./a.out

constructor. 1000000
destructor.
n:0
*/

相关内容

william 支付宝支付宝
william 微信微信
0%