Open3

C++で色々確認するメモ

hzuikahzuika

Copy/Move constructor, Destructor の動作を確認する。

#include <iostream>
#include <stack>

class A {
public:
    static int count;
    A() {
        m_count = count;
        std::cout << "Constructor" << m_count << std::endl;
        count++;
    }
    
    A(const A &obj){
        m_count = count;
        std::cout << "Copy Constructor" << m_count << std::endl;
        count++;
    }
    
    A(A &&a){
        m_count = a.m_count;
        std::cout << "Move Constructor" << m_count << std::endl;
    }
    
    ~A() {
        std::cout << "Destructor" << m_count <<  std::endl;
    }
    int m_count;
};

int A::count = 0;

int main() {
    std::stack<A> stack;
    
    A a;
    stack.push(a);
    stack.push(A());
    std::cout << "before clear stack" << std::endl;
    stack = std::stack<A>();
    std::cout << "before return" << std::endl;
    return 0;
}
Constructor0
Copy Constructor1
Constructor2
Move Constructor2
Destructor2
before clear stack
Destructor1
Destructor2
before return
Destructor0
hzuikahzuika

空のstackのtop()を呼び出すとSegmentation fault

#include <iostream>
#include <stack>

int main() {
    std::stack<int> stack;
    int a = stack.top();
    return 0;
}
Segmentation fault